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.

    extraParametersAdditional parameters to pass along to the event handler.

  • version added: 1.3.trigger( event )

    eventA jQuery.Event object.

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');

As of jQuery 1.3, .trigger()ed events bubble up the DOM tree; an event handler can stop the bubbling by returning false from the handler or calling the .stopPropagation() method on the event object passed into the event. Although .trigger() simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.

To trigger handlers bound via jQuery without also triggering the native event, use .triggerHandler() instead.

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, these parameters will be passed along to the handler as well. To pass more than one parameter, use an array as shown here. As of jQuery 1.6.2, a single parameter can be passed without using an array.

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.

The .trigger() method can be used on jQuery collections that wrap plain JavaScript objects similar to a pub/sub mechanism; any event handlers bound to the object will be called when the event is triggered.

Note: For both plain objects and DOM objects, if a triggered event name matches the name of a property on the object, jQuery will attempt to invoke the property as a method if no event handler calls event.preventDefault(). If this behavior is not desired, use .triggerHandler() instead.

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: Alternative way to pass data through an event object:

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

});

Support and Contributions

Need help with .trigger() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .trigger()? Report it to the jQuery core team.

Found a problem with this documentation? Report it on the GitHub issue tracker

  • Anonymous

    trigger() has an additional mode: it can take a jQuery Event object, in addition to taking an event string.

  • Anonymous

    It does not work for hyperlinks:
    $(‘a’).trigger(‘click’);
    why?

    • hyphan

      Maybe browsers prevent it for security reasons? Had to use window.location.href too..

    • http://livingstonsamuel.com/ Livingston Samuel

      $('a').trigger('click') or $('a').click() will not trigger the default behavior on a link, even if nothing else is preventing it

    • Anonymous

      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.

    • Rabo

      @sterba – Why not just do $(‘a’).click() ?

      • http://www.brainonfire.net/ Tim McCormack

        That's irrelevant. sterba is asking why the default behavior is not triggered.

  • 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.

    • Anon

      Binding and triggering events on non-DOM objects do work, but they cannot be unbound either through .unbind() or .one()

  • 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

    • eric

      You should use triggerHandler().

  • Ricardo

    If you bind a name event like “change.mask” and call trigger( “change.mask” ) it only works once, is that right?

  • http://mo.notono.us Oskar Austegard

    The description and syntax listing needs to be updated to reflect that you can also pass an event to the function, as illustrated in the examples. Besides confusing developers, the omission also confuses jquerylint…

  • http://www.saliences.com/ Sahab Yazdani

    One thing that is confusing is that trigger tries to call a default event handler even for custom events. This isn't captured in the documentation. So if you have an object like so:

    var o = { remove: function() { alert('the last resort!'); } };

    and then try to bind and trigger a “remove” event on it:

    $(o).bind( 'remove', function() { alert('the first resort'); } );
    $(o).trigger('remove');

    The browser will show two alert windows, the first with the text: “the first resort”, and the second with the text: “the last resort!”.

    This isn't really captured anywhere in the documentation for this method and to be honest seems more like a bug to me, so I'm just listing it out here in case anybody else was also left scratching their heads for an hour or two.

    • AnotherStupidPseudo

      I have the exact same problem.
      I’m trying to write a jQuery plugin for HTML 5 Video ( with fallbacks) but the problem is
      the Video Element (the HTML Node) has a method ( a property ?) called “play”.
      So when I add a “play” method to the jQuery.fn object and then try to trigger a “play” event on a video element, the event is fired twice !

      For example, I create a new method called “play” :
      jQuery.fn.play = function( fn ) {
      return (fn) ? this.bind( “play”, fn ) : this.trigger( “play”);
      };
      and then I try to use it :
      $(“video”).play(function() { alert(‘failed’) });
      The browser shows two alert windows.

      Can anyone help ?

      • http://www.learningjquery.com/ Karl Swedberg

        Try using the triggerHandler() method instead.

        • AnotherStupidPseudo

          I tried that, but unfortunately it only works too well ,in a way.
          Using triggerHandler() also prevents the default action, which in this case is playing the video. So when the event occurs, only alert is shown but the video isn’t played >.<

          But thanks for the suggestion. If you have another idea, I'll be glad to hear it.

  • BASTA!

    Can a jQuery please state decisively here whether trigger()

    – is supposed to trigger default processing and does in fact trigger it?
    – is supposed to trigger default processing but fails to do so because of a bug?
    – is NOT supposed to trigger default processing and in fact does not trigger it?
    – is NOT supposed to trigger default processing but does because of a bug?

  • http://www.learningjquery.com/ Karl Swedberg

    Using .trigger('click') will not trigger the native click event. To simulate a default click, you can bind a click handler like so:

    $(‘#someLink’).bind(‘click’, function() {
    window.location.href = this.href;
    return false;
    });

    … where “someLink” is an actual selector of your choice.

    You can then trigger that bound click handler if you want, based on some other interaction.

    $(‘input.mycheckbox’).click(function() {
    if (this.checked) {
    $(‘#someLink’).trigger(‘click’);
    }
    });

  • Qianxuechao

    How to trigger click event of with firefox?

    $(“#uploadFile”).trigger(“click”);

    it does not work with firefox, but ok with IE.

  • vativa

    $(‘#inputFile’).trigger(‘click’) doesn’t work in Firefox (Mac OS X). Any ideas? Thanks…

    • Noorsulayman

      Same here but also in IE7 in Windows

  • http://twitter.com/1st8 Christoph Geschwind

    To trigger a global event, which fires on all bound elements, use the following:
    $.event.trigger('eventName');

  • Rich

    I believe this page is missing a bit of vital information: 'Triggered events now bubble up the DOM.' http://docs.jquery.com/Release:jQuery_1.3#Changes

  • http://twitter.com/JackReichert Jack Reichert

    HI I'm using the following command.

    $(window).trigger('hashchange');

    It's working fine in most browsers. Just not in firefox 3.6 in windows.

    Any ideas?

    The idea is to initiate a function as if the hash was changed on a page load.

  • http://pulse.yahoo.com/_RGWFPQFSQHH2KWJGHM5JX6EBBU Seamus Leahy

    If you are using a custom object as the source for a custom event and you find the bound functions get called multiple times, it might be an issue if your custom object has a “length” propriety.

    var o = {length: 3};
    $(o).bind( 'custom', function(){ console.log('hi') } );
    $(o).trigger('custom');

    // Output
    hi
    hi
    hi

  • Noorsulayman

    areadiv.find('input').each(function(){
    if ($(this).attr('value') == 'Cancel'){
    $(this).trigger('click');
    }
    });

    doesn't work in IE7

  • Stephan Beal

    The Button #2 clicked demo is broken: clicking button 2 also updates the value for the Button #1 clicks. Or it does in Chrome 7, anyway.

    • Rd

      Exactly as intended – hence the title “Example: Clicks to button #2 also trigger a click for button #1.”

  • badsyntax

    It won't be possible to adjust the target in the event passed into the trigger'ed method. The target will always be the element you trigger'ed. I've tried all the methods described in this page to adjust the event target but had no luck. (It would be cool if we could change the event target, but I can't say much more without understanding the constaints.)

  • Bhargava Ch

    Can any one help me Trigger() is not supporting in fire fox ? And please don't use any windows.href

  • King_wgj

    I just used the function .trigger(“click”),but it doesnt work in IE6 ,but IE8 it works

    how to solve this probem ?

  • mrbinky3000

    I have a question. I have 8 buttons that have unique incrementing id's and a shared class.

    <button class=”btnChapter” id=”btnChapter_1″ value=”1″>1</button>
    <button class=”btnChapter” id=”btnChapter_2″ value=”2″>2</button>
    <button class=”btnChapter” id=”btnChapter_3″ value=”3″>3</button>

    In order to prevent me from duplicating code, I bound a click event to the btnChapter class.

    $('.btnChapter').click(function(){ .. do stuff .. });

    How do I trigger() only #btnChapter_2? The following doesn't seem to work.

    $('#btnChapter_2').click() does nothing.

    • http://twitter.com/jesperspeedway Jesper Veldhuizen

      $('#btnChapter_2').trigger('click');

  • King_wgj

    hi , everyone,I have a question about trigger and javascript 'winow.open(..);

    if I use trigger to call a funtion which contains 'window.open(…), it doesn't work in IE6,but it works in FireFox. to be surprised ,it works both using IE and Firefox when I click the button using mouse. how to solve this problem ?

  • King_wgj

    hi , everyone,I have a question about trigger and javascript 'winow.open(..);

    if I use trigger to call a funtion which contains 'window.open(…), it doesn't work in IE6,but it works in FireFox. to be surprised ,it works both using IE and Firefox when I click the button using mouse. how to solve this problem ?

  • Asd

    Apparently .trigger('submit') wont work if you have the id OR the name set to “submit” for a form element. This differs from other cases because they all said that only the name attribute cant have that value.

  • salomvary

    It should also be mentioned that events triggered on detached elements (not part of their ownerDocument's dom tree) fire event handlers attached to their ownerDocument despite the fact that ownerDocument is not on the element's “parent chain”.

    Example:
    jQuery(document).bind('foo', function() { console.log('foo triggered on document'); });
    jQuery('<div>').trigger('insert');

    Console output:
    foo triggered on document</div>