The trigger method
The trigger method runs all event handlers attached to an element for events of a given type. It calls the handler functions in the order they would be called by the user. If you want to call an event handler but not execute the standard event, use the triggerHandler method.
Syntax
As the first parameter we can pass the event type as a string, and as the second (optional) parameter we can pass an array or object containing additional parameters to pass to the handler:
$(selector).trigger(event type, [additional parameters]);
You can pass an event as the first parameter in the form of a jQuery.Event object:
$(selector).trigger(event, [additional parameters]);
There is a difference between passing additional parameters to the trigger method and data to the on method. In the first case, the data must be defined during the event execution, and in the second case, already at the time of binding the handler function.
Example
When you click the #first button, the value will increase only in the first span, when you click the #second button, it will increase in both spans, simulating a user click on the first one. The increase function will increase the number passed to it as a parameter by 1. Using the trigger method, we make the click event also trigger in the first span, although we click the #second button:
<button id="first">button1</button>
<button id="second">button2</button>
<div><span>0</span></div>
<div><span>0</span></div>
button {
margin: 10px;
}
div {
margin-left: 10px;
font-weight: bold;
}
span {
color: green;
}
$('#first').click(function() {
increase($('span').first());
});
$('#second').click(function() {
$('#first').trigger('click');
increase($('span').last());
});
function increase(str) {
let num = parseInt(str.text(), 10);
num.text(num + 1);
}
See also
-
method
on,
which allows you to bind an event handler to an element -
method
triggerHandler,
which allows you to run all event handlers attached to an element -
object
event,
which contains information about the event -
method
submit,
which allows you to bind a handler to the JavaScript submit event or trigger this event