Passing Extra Parameters to jQuery Custom Events
This guide explains how to send and receive additional parameters
when working with custom event handlers in jQuery. You will learn how to
pass data arrays using the .trigger() method, how the event
listener receives those values as distinct arguments alongside the
standard event object, and how to pass static data at the time of
binding using .on().
Passing Parameters with
.trigger()
The most common way to pass extra parameters to a custom event
handler is by supplying them as an array in the second argument of the
.trigger() or .triggerHandler() method.
When triggering the event, wrap your arguments in an array:
// Trigger a custom event named 'userLogin' with two extra parameters
$('#userProfile').trigger('userLogin', ['JohnDoe', 'admin']);Receiving Parameters in the Event Handler
When listening for the custom event using .on(), the
first parameter passed to the callback function is always the jQuery
event object. Any additional parameters defined in your
trigger array are passed as subsequent arguments in the exact order they
were provided.
// Attach the custom event listener
$('#userProfile').on('userLogin', function(event, username, role) {
console.log('Event Type:', event.type);
console.log('Username:', username); // Outputs: JohnDoe
console.log('Role:', role); // Outputs: admin
});If you only pass a single parameter that is not an array, jQuery will still deliver it to the handler, but wrapping values in an array is the recommended practice to prevent unexpected behavior with complex types like objects.
Passing Objects as Parameters
You can also pass complex data structures, such as JavaScript objects, within the parameter array:
// Passing an object
var metadata = { id: 101, status: 'active' };
$('#userProfile').trigger('userUpdate', [metadata]);
// Handling the object
$('#userProfile').on('userUpdate', function(event, data) {
console.log('User ID:', data.id); // Outputs: 101
console.log('Status:', data.status); // Outputs: active
});Passing Data at Binding
Time (event.data)
If you need to pass data to the event handler when the listener is
attached rather than when it is triggered, pass the data object as the
second argument to the .on() method. This data is accessed
inside the handler via event.data:
// Binding with static data
$('#userProfile').on('userLogout', { reason: 'session_timeout' }, function(event) {
console.log('Logout reason:', event.data.reason);
});
// Triggering without additional arguments
$('#userProfile').trigger('userLogout');