14

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Joe Ng'ethe
  • 874
  • 2
  • 12
  • 26
  • Well, when you click on the body, you issue a click event which presumably bubbles up to the body and issues a click event which presumably bubbles up to the body and issues a click event... – VLAZ Sep 21 '16 at 15:24
  • Also, you are missing a closing quote. – VLAZ Sep 21 '16 at 15:25

1 Answers1

25

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');});
A. Wolff
  • 74,033
  • 9
  • 94
  • 155