How to Trigger Events with jQuery
This guide explains how to programmatically trigger events on DOM
elements using jQuery. You will learn how to use the core
.trigger() method to fire both native and custom events,
utilize common shorthand methods, pass custom data to event handlers,
and understand the functional differences between
.trigger() and .triggerHandler().
Using the .trigger()
Method
The primary way to execute an event on a selected element is the
.trigger() method. It executes all handlers and behaviors
attached to the matched elements for the given event type, and the event
bubbles up the DOM tree.
// Triggering a native click event
$('#myButton').trigger('click');
// Triggering a change event on an input
$('#myInput').trigger('change');Using Shorthand Methods
For standard browser events (like click,
focus, blur, submit), jQuery
provides dedicated shorthand methods. Calling these methods without
arguments triggers the event immediately.
// Programmatically submit a form
$('#loginForm').submit();
// Programmatically focus an input field
$('#username').focus();
// Programmatically click a button
$('#submitBtn').click();Passing Custom Data with
.trigger()
You can pass extra parameters to an event handler by providing an
array of arguments as the second parameter to
.trigger().
// Event listener expecting custom data
$('#statusMessage').on('updateStatus', function(event, message, statusType) {
console.log(statusType + ': ' + message);
});
// Triggering the custom event with data
$('#statusMessage').trigger('updateStatus', ['Operation successful!', 'SUCCESS']);Using
.triggerHandler() for Isolated Execution
When you want to run an element's attached event handlers without
triggering the browser's default behavior or allowing the event to
bubble up the DOM, use .triggerHandler().
Key differences with .triggerHandler():
- It only triggers the event on the first matched element in the jQuery object.
- It prevents the browser's default action (for example, calling
.triggerHandler('submit')on a form runs the validation function but does not actually submit the form to the server). - The event does not bubble up the DOM hierarchy.
// Runs the focus handler without physically focusing the input
$('#myInput').triggerHandler('focus');