Click an element using triggerHandler()
works:
$element = $('#gwt-debug-location-pill-edit-div:visible');
$element.triggerHandler('click');
But, clicking it using trigger()
, doesn't:
$element.trigger('click');
Why is that?
To replicate this (in Firefox and Chrome):
- Go to https://adwords.google.com/select/home, and log in using your credentials
- Tools and Analysis
->
Keyword Planner - Expand "Enter or upload keywords to see how they perform"
- Using browser's console, try to click on the locations box (marked in red in the screenshot below) via the two methods above (you'll need to inject jQuery into the page. I used jQuerify to do that.)
Let's compare
jQuery.fn.trigger
andjQuery.fn.triggerHandler
:The only real difference is the fourth argument,
true
, given tojQuery.event.trigger
withtriggerHandler
.Looking at
jQuery.event.trigger
, the argument is calledonlyHandlers
, and among other things, the documentation oftriggerHandler
notes that:We can see where the default behaviour is actually triggered:
In the case that
onlyHandlers
is false (trigger()
), and no event handler stopped the default event from executing, the default action will then be executed.With
onlyHandlers
being true (triggerHandler()
), this will never happen.So, for the
trigger()
case, it ends up executingclick()
on the target element, which triggers the state change correctly—but it turns out that, in both thetrigger()
andtriggerHandler()
cases, the click was already correctly fired up in the loop through the eventPath above:So
trigger('click')
ends up clicking the element twice (!) — presumably becauseclick()
doesn't return false, so the event default action is never prevented — whereastriggerHandler('click')
only does it once.This can be verified by stepping through the
jQuery.event.trigger
method with the inspector and seeing the selector open, then close again.The question is if this what we should generally expect; it seems strange that an otherwise-working event trigger would cause double triggers in the case of a DOM-only reaction.