jQuery trigger()
Method
Example
Trigger the select event on an <input>
element:
$("button").click(function(){
$("input").trigger("select");
});
Definition and Usage
The trigger()
method triggers the specified event and the default behavior of that event (such as form submission) on the selected elements.
This method is similar to the triggerHandler() method, except that triggerHandler()
does not trigger the default behavior of the event.
Differences compared to the triggerHandler()
method:
trigger()
does not cause the default behavior of the event (such as form submission).trigger()
operates on all matched elements in the jQuery object, whereastriggerHandler()
only affects the first matched element.Events created by
triggerHandler()
do not bubble up the DOM tree; if the target element does not directly handle them, nothing happens.
Example
Comparison between triggerHandler()
and .trigger()
:
$( "#old" ).click(function() {
$( "input" ).trigger( "focus" );
});
$( "#new" ).click(function() {
$( "input" ).triggerHandler( "focus" );
});
$( "input" ).focus(function() {
$( "<span>Focused!</span>" ).appendTo( "body" ).fadeOut( 1000 );
});
Syntax
Parameter | Description |
---|---|
event | Required. Specifies the event to trigger on the specified element. <br>Can be a custom event or any standard event. |
param1, param2, ... | Optional. Additional parameters to pass to the event handler. <br>Extra parameters are particularly useful for custom events. |
More Examples
Passing Additional Parameters to Custom Events
Differences Between trigger()
and triggerHandler()