jQuery make entire div clickable

Open link if user clicked anywhere in the block.

jQuery:


jQuery(function ($) { // wait while jQuery loads (document-ready)

    $('.block').click(function () { // open the link if user clicked anywhere on block 

        var link_url = $(this).find('a').attr('href');

        var target_attr = $(this).find('a').attr('target');

        if (target_attr == '_blank') {

            window.open(link_url);

        } else {

            window.location.href = link_url;

        }

    });

});

css:


.block {

    display: inline-block;

    padding: 40px;

    margin: 20px;

    border: 2px solid #555;

    background: #ffa;

}

.block:hover {

    cursor: pointer;

    background: orange;

}

html:


<div class="block"> <a href="https://www.google.com/">Google link</a>



    <p>Sample text.</p>

</div>

<div class="block"> <a href="http://en.wikipedia.org/wiki/Wikipedia" target="_blank">Wikipedia link - opens in new window</a>



    <p>Sample text.</p>

</div>

Leave a Comment