iamserious
iamserious

Reputation: 5475

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.

Upvotes: 4

Views: 3321

Answers (5)

GrahamJRoy
GrahamJRoy

Reputation: 1643

Instead of using the click event on the child node, just set the browser location to the href value

$('div.class').click(function(){
  location = $(this).find('a').attr('href');
});

Upvotes: 1

Ady Ngom
Ady Ngom

Reputation: 1302

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');
});

 

Upvotes: 4

Sang Suantak
Sang Suantak

Reputation: 5265

Use the event.stopPropagation() method.

Upvotes: 3

sv_in
sv_in

Reputation: 14049

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

You need to add the event argument and a stopPropagation method to the handler.

Upvotes: 0

tomfumb
tomfumb

Reputation: 3759

How about this?

$('selector').attr('onclick')()

Upvotes: 1

Related Questions