Turn an Entire DIV into a Clickable Link

If you have been to a Pinterest like site that uses the grid masonry style layout, you may have noticed that one can hover over any region inside the box and its clickable.

A typical DIV is written using the following markup

<div class="box">
    <h2>Box Title</h2>
    <p>The Quick Brown Fox Jumped Over The Lazy Dog</p>
    <p><a class="divLink" href="http://www.labnol.org/">Webpage URL</a></p>
</div>

There’s a outer DIV and it has elements like the title, description and a link. The requirement is that when someone hovers their mouse over the DIV, it should point to the hyperlink that’s contained inside the DIV.

This can be done in two ways – using CSS or using jQuery.

The CSS approach – Make the Whole DIV clickable

<style type="text/css">
div.box {
    position: relative;
    width: 200px;
    height: 200px;
    background: #eee;
    color: #000;
    padding: 20px;    
}

div.box:hover {
    cursor: hand;
    cursor: pointer;
    opacity: .9;
}

a.divLink {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    text-decoration: none;
    /* Makes sure the link doesn't get underlined */
    z-index: 10;
    /* raises anchor tag above everything else in div */
    background-color: white;
    /*workaround to make clickable in IE */
    opacity: 0;
    /*workaround to make clickable in IE */
    filter: alpha(opacity=0);
    /*workaround to make clickable in IE */
}

Here we assign an absolute position to the inner <a> tag such that it occupies the entire DIV and we also set the z-index property to 10 to position the link above all the other elements in the DIV. This is the easiest approach and the semantic structure is maintained.

jQuery – Make Div Clickable

Here we use jQuery to determine the hyperlink of the first a element inside the DIV and redirects the user to that link when the DIV is clicked.

The cursor properties of the DIV are sent to “pointer” on hover to indicate to the user that the DIV is clickable. Similarly, the text in the status bar is changed to the URL that the DIV is pointing to.

$(document).ready(function () {

    // Open in new window
    $(".box1").click(function () {
        window.open($(this).find("a:first").attr("href"));
        return false;
    });
        
    // Or use this to Open link in same window (similar to target=_blank)
    $(".box1").click(function(){
        window.location = $(this).find("a:first").attr("href");
        return false;
    });

    // Show URL on Mouse Hover
    $(".box1").hover(function () {
        window.status = $(this).find("a:first").attr("href");
    }, function () {
        window.status = "";
    });

});