jQuery trigger click gives "too much recursion" jQuery trigger click gives "too much recursion" jquery jquery

jQuery trigger click gives "too much recursion"


The problematic bit of your code is this:

$("div.boxContent") /* miss the each function */.click(function() {    $(this).find("div.btn a").trigger('click');});

This says "every time any click event is received on this element, trigger a click on the descendant element". However, event bubbling means that the event triggered in this function is then handled again by this event handler, ad infinitum. The best way to stop this is, I think, to see if the event originated on the div.btn a element. You could use is and event.target for this:

$("div.boxContent") /* miss the each function */.click(function(event) {    if (!$(event.target).is('div.btn a')) {        $(this).find("div.btn a").trigger('click');    }});

This says "if the click originated on any element apart from a div.btn a, trigger a click event on div.btn a. This means that events caused by the trigger call will not be handled by this function. This is superior to checking event.target == this (as Andy's answer has it) because it can cope with other elements existing within the div.boxContent.


A cleaner way to solve this is to take the the element you are triggering the click on to and put it outside of the triggered element:

So if you have this:

<div class="boxContent">    <div class="btn">        <a href="#">link</a> <!-- move this line... -->    </div></div><!-- ... to here. --><script>$("div.boxContent") /* miss the each function */    .click(function() {    $(this).find("div.btn a").trigger('click');});</script>

By moving the "div.btn a" tag outside of the "boxContent" div. You avoid the recursion loop all together.