jQuery API

.trigger()

.trigger( eventType, extraParameters ) Returns: jQuery

Description: Execute all handlers and behaviors attached to the matched elements for the given event type.

  • version added: 1.0.trigger( eventType, extraParameters )

    eventTypeA string containing a JavaScript event type, such as click or submit.

    extraParametersAn array of additional parameters to pass along to the event handler.

Any event handlers attached with .bind() or one of its shortcut methods are triggered when the corresponding event occurs. They can be fired manually, however, with the .trigger() method. A call to .trigger() executes the handlers in the same order they would be if the event were triggered naturally by the user:

$('#foo').bind('click', function() {
      alert($(this).text());
    });
    $('#foo').trigger('click');

While .trigger() simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.

When we define a custom event type using the .bind() method, the second argument to .trigger() can become useful. For example, suppose we have bound a handler for the custom event to our element instead of the built-in click event as we did above:

$('#foo').bind('custom', function(event, param1, param2) {
  alert(param1 + "\n" + param2);
});
$('#foo').trigger('custom', ['Custom', 'Event']);

The event object is always passed as the first parameter to an event handler, but if additional parameters are specified during a .trigger() call as they are here, these parameters will be passed along to the handler as well.

Note the difference between the extra parameters we're passing here and the eventData parameter to the .bind() method. Both are mechanisms for passing information to an event handler, but the extraParameters argument to .trigger() allows information to be determined at the time the event is triggered, while the eventData argument to .bind() requires the information to be already computed at the time the handler is bound.

Examples:

Example: Clicks to button #2 also trigger a click for button #1.

<!DOCTYPE html>
<html>
<head>
  <style>

button { margin:10px; }
div { color:blue; font-weight:bold; }
span { color:red; }
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
	<button>Button #1</button>
<button>Button #2</button>
<div><span>0</span> button #1 clicks.</div>

<div><span>0</span> button #2 clicks.</div>
<script>
$("button:first").click(function () {
update($("span:first"));
});
$("button:last").click(function () {
$("button:first").trigger('click');

update($("span:last"));
});

function update(j) {
var n = parseInt(j.text(), 10);
j.text(n + 1);
}
</script>
</body>
</html>

Demo:

Example: To submit the first form without using the submit() function, try:

$("form:first").trigger("submit")

Example: To submit the first form without using the submit() function, try:

var event = jQuery.Event("submit");
$("form:first").trigger(event);
if ( event.isDefaultPrevented() ) {
// Perform an action...
}

Example: To pass arbitrary data to an event:

$("p").click( function (event, a, b) {
// when a normal click fires, a and b are undefined
// for a trigger like below a refers to "foo" and b refers to "bar"

} ).trigger("click", ["foo", "bar"]);

Example: To pass arbitrary data through an event object:

var event = jQuery.Event("logged");
event.user = "foo";
event.pass = "bar";
$("body").trigger(event);

Example: Alternate way to pass data through an event object:

$("body").trigger({
type:"logged",
user:"foo",
pass:"bar"

});

Comments

  • Support requests, bug reports, and off-topic comments will be deleted without warning.

  • Please do post corrections or additional examples for .trigger() below. We aim to quickly move corrections into the documentation.
  • If you need help, post at the forums or in the #jquery IRC channel.
  • Report bugs on the bug tracker or the jQuery Forum.
  • Discussions about the API specifically should be addressed in the Developing jQuery Core forum.
  • axdr
    -
  • dima
    I was trying to use .trigger with a checkbox input, and there seems to be a problem:

    $('#mybox').bind('click', function(e) { alert(e.target.checked); });
    $('#mybox').click();

    If the checkbox is unchecked initially, the alert message will say 'false' first, and then the checkmark will appear. It seems that the handler is called before the state changes.
    Clicking on the same checkbox with a mouse, first changes the state, and then invokes handler.
    This is a big problem, because there is no way for the callback to know which state the input is going to be in if the even can be fired either programmatically or via gui
  • @sterba :
    I think it's because of the fact that .trigger() command does not cause an event to be fired. It just calls the handler as a normal function. In other word, .trigger() command is just a handy way to call an event handler, not to emulate an event.
  • dima
    well, if that was the case, the state of the button would not change at all, but that's not what happens - the state does change, just not until after the handler is called.
    There is actually another call, specifically intended to invoke handlers without actually firing the event - .triggerHandler()
    I am using it currently as a workaround for this problem.
  • ramico
    it is not enough to have a costume event without actual calling to something
    i mean we have to issue the pressing of a button not the calling of the elevator only because typical methods could do that

    i know that there has to be a part of code where to like 'physically press the button' where a button is just pressed down

    and the handler should go behind it 'what is next'
  • Mike D.
    You can use this mechanism to trigger events from your custom classes as well. To trigger an event from within your class, use $(this).trigger('myCustomEvent', [ param1, param2, etc. ]); To subscribe to such an event, use var myObj = new CustomObject(); $(myObj).bind('myCustomEvent', myEventHandler); The documentation implies that you can only bind/trigger on DOM elements, but I have tried this successfully.
  • sterba
    It does not work for hyperlinks:
    $('a').trigger('click');
    why?
  • sterba
    Yes Samuel, you`r right. After while I think, that it`s intended to do so: just to trigger onclick, but no the default behavior.
  • $('a').trigger('click') or $('a').click() will not trigger the default behavior on a link, even if nothing else is preventing it
  • hyphan
    Maybe browsers prevent it for security reasons? Had to use window.location.href too..