Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unwanted recursion - how to avoid child click event from passing to parent in jquery?

I have a some elements, roughly like this:

<div>
    <a>
<div>

When a user clicks anywhere on the div, I want the a element to be clicked - for usability purposes.

Simple right? So I wrote this:

$('div.class').click(function(){  
    $('a.class', this).click();
    console.log('clicked'); 
});

Trouble is, this clicks the a element alright, but the event propagates to the div, which clicks it, which clicks the a, which... well you can see where it's going.

I cooked up a sample on JSfiddle here but it doesn't show the console log. So if you click, Firebug doesn't show anything. but my local site sets Firebug crazy with logs (clicked) so much that in the end script gets killed saying too much recursion on this page

How do I stop this recursion?

Yes I know, I know that I can use window.location for this purpose, but clicking the link does some extra work and also uses window history for browsers, so I really want to click that vicious a without making it click its Dad. Or Mom. Or whatever that div is.

PLEASE READ

Since everyone is suggesting the same thing over and over again, and it's not working, please take a look this JSfiddle. Try it and see if it works before you answer. When you click on a div, Google should load up. That's what I'm looking for.

like image 529
iamserious Avatar asked Jan 20 '23 23:01

iamserious


2 Answers

If this is is your markup:

<div>
    <a></a>
</div>

...all you will need to do is in your css do something like:

div a { display: block};

The anchor element will then stretch and occupy all the available space in the parent div. However, if some other elements exist within that div, you could do:

$('a.class').click(function(event){
   event.stopPropagation();
   alert('you clicked on me');
});

$('div.class').click( function () {
  $(this).children('a.class').trigger('click');
});

 
like image 88
Ady Ngom Avatar answered Jan 22 '23 11:01

Ady Ngom


Use the event.stopPropagation() method.

like image 35
Sang Suantak Avatar answered Jan 22 '23 12:01

Sang Suantak