Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum range error on click event in jQuery

Tags:

jquery

I have a reproducable error here, where I run into a Uncaught RangeError: Maximum call stack size exceeded

It's just a click event I call onto a link.

My HTML:

<div id="box">
    <a href="#">test</a>
</div>

My Javascript:

$('#box').click(function() {
    ("a", $(this)).click();
});

Now, clicking the #box leads to an error.

http://jsfiddle.net/DMAMv/2/

like image 493
Chrisissorry Avatar asked Sep 21 '11 16:09

Chrisissorry


3 Answers

mine was a list item in a dropdown so i wanted the event to keep bubbling so the dropdown would be closed. this is the solution i used:

$('div#outer').click(function (e) {
   if (e.target == e.currentTarget) // prevents bubbled events from triggering
      $($(e.currentTarget).children()[0]).trigger('click');
});
like image 105
Brad Avatar answered Nov 15 '22 07:11

Brad


You should stop the propagation with stopImmediatePropagation(), otherwise you have too much rcursion

$('#box').click(function() {
    $("a:first", this).click();
});
$('a').click(function(e){
   e.stopImmediatePropagation();
   alert('hi');
});

fiddle http://jsfiddle.net/DMAMv/8/

like image 25
Nicola Peluchetti Avatar answered Nov 15 '22 06:11

Nicola Peluchetti


That's because it is recursively triggering the click event. This is caused by two problems.

The first is this innocent looking line:

("a", $(this)).click();  # note the missing $ at the beginning

That essentially reduces to $(this).click() (because the comma operator evaluates both operands and returns the second one) and so your click event on #container triggers itself. Consider the following examples - http://jsfiddle.net/2VnbG/ and http://jsfiddle.net/2VnbG/1/ - notice how the parent div is targetted when the $ is missing.

Prepend the line with the missing $ to solve that issue, i.e. $("a", $(this)).click();

The next problem is that a click event on the anchor will bubble up to the parent object (in your case, #container). If the parent has a bound function on the click event which triggers a new event, then the cycle is going to repeat infinitely.

To solve that, use event.stopPropagation() to stop the event from bubbling up the DOM tree.

Here's an example with the above fixes in place: http://jsfiddle.net/DMAMv/9/

like image 24
Shawn Chin Avatar answered Nov 15 '22 08:11

Shawn Chin