Joey Ng'ethe Joey Ng'ethe - 2 months ago 20
jQuery Question

Maximum call stack size exceeded on trigger click

I really want to do something simple. On click on a certain element, i trigger a click on another element but i get the below error on my console.

Uncaught RangeError: Maximum call stack size exceeded


My code is as below;

$('body').on('click', '.actual-click-element', function(event) {
$('.trigger-click-element').trigger('click);
event.preventDefault();
});


I wonder why am am getting this error and i don't see how this is recursive. Any ideas?

Answer

Surely because .trigger-click-element is descendant of .actual-click-element...

To avoid recursive call, you could use jq triggerHandler():

Events triggered with .triggerHandler() do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.

$('body').on('click', '.actual-click-element', function(event) { 
    $('.trigger-click-element').triggerHandler('click');
    event.preventDefault(); 
});

Now if $('.trigger-click-element') returns more than one element, you could use:

$('.trigger-click-element').each(function(){$(this).triggerHandler('click');});
Comments