jQuery trigger() vs triggerHandler() Differences
When developing with jQuery, simulating events programmatically is a
routine task, typically accomplished using either trigger()
or triggerHandler(). While both methods invoke event
listeners bound to target elements, they behave differently under the
hood. The primary distinctions lie in how they handle event bubbling,
default browser behaviors, the number of matched DOM elements affected,
and the values they return for method chaining. Understanding these
differences ensures you choose the correct method for your specific
JavaScript logic.
1. Number of Elements Affected
trigger(): Executes the specified event on all elements matching the jQuery selector.triggerHandler(): Executes the specified event only on the first element in the matched jQuery collection.
// Triggers the 'click' event on every button on the page
$('button').trigger('click');
// Triggers the 'click' event only on the first button found
$('button').triggerHandler('click');2. Event Bubbling
trigger(): The triggered event bubbles up through the DOM tree. Parent elements with matching delegated listeners will also catch and process the event.triggerHandler(): The event does not bubble up the DOM hierarchy. Only the handlers directly attached to the first matched element will execute.
3. Default Browser Behaviors
trigger(): Triggers both the bound jQuery event handlers and the browser's default behavior for that event (such as submitting a form or checking a checkbox), unlessevent.preventDefault()is invoked within a handler.triggerHandler(): Suppresses the browser's default action entirely. For instance, calling.triggerHandler('submit')on a<form>executes any custom submit handlers attached via jQuery, but the browser will not physically submit the form or reload the page.
4. Return Values and Method Chaining
trigger(): Returns the original jQuery object, allowing you to chain additional jQuery methods afterward.triggerHandler(): Returns the value returned by the last event handler executed, rather than a jQuery object. If no handler exists or the handler returns nothing, it returnsundefined. Because it returns raw data, it breaks jQuery method chaining.
// trigger() maintains jQuery chaining
$('#myInput').trigger('focus').addClass('active');
// triggerHandler() returns the handler's return value
$('#myInput').on('customCheck', function() {
return true;
});
let result = $('#myInput').triggerHandler('customCheck');
console.log(result); // true (cannot chain jQuery methods here)Summary Comparison
| Feature | trigger() |
triggerHandler() |
|---|---|---|
| Target Elements | All elements in selection | Only the first element |
| DOM Bubbling | Yes | No |
| Default Action | Executes | Suppressed |
| Return Value | jQuery object (chainable) | Handler's return value |