Add click event to Div and go to first link found

15,211

Solution 1

Depending on how many of these div.click elements you have, you may want to use event delegation to handle these clicks. This means using a single event handler for all divs that have the click class. Then, inside that event handler, your callback acts based on which div.click the event originated from. Like this:

$('#div-click-parent').click(function (event)
{
    var $target = $(event.target); // the element that fired the original click event
    if ($target.is('div.click'))
    {
        window.location.href = $target.find('a').attr('href');
    }
});

Fewer event handlers means better scaling - more div.click elements won't slow down your event handling.

Solution 2

optimized delegation with jQuery 1.7+

$('#div-click-parent').on('click', 'div.click', function () {
   window.location.href = $(this).find('a').attr('href');
});

Solution 3

Instead of binding all the clicks on load, why not bind them on click? Should be much more optimal.

$(document).ready(function() {
   $('.click').click(function() {
        window.location = $(this).children('a:first').attr('href');
        return false;
    });
});
Share:
15,211
Xavi Esteve
Author by

Xavi Esteve

Creating websites since 1999

Updated on June 04, 2022

Comments

  • Xavi Esteve
    Xavi Esteve almost 2 years

    I think I've been too much time looking at this function and just got stuck trying to figure out the nice clean way to do it.

    It's a jQuery function that adds a click event to any div that has a click CSS class. When that div.click is clicked it redirects the user to the first link found in it.

    function clickabledivs() {
        $('.click').each(
            function (intIndex) {
                $(this).bind("click", function(){
                    window.location = $( "#"+$(this).attr('id')+" a:first-child" ).attr('href');
                });
            }
        );
    }
    

    The code simply works although I'm pretty sure there is a fairly better way to accomplish it, specially the selector I am using: $( "#"+$(this).attr('id')+" a:first-child" ). Everything looks long and slow. Any ideas?

    Please let me know if you need more details.

    PS: I've found some really nice jQuery benchmarking reference from Project2k.de here: http://blog.projekt2k.de/2010/01/benchmarking-jquery-1-4/