jQuery: The Write Less, Do More JavaScript Library

Events/trigger

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Events

trigger( type, [data] )

Trigger a type of event on every matched element.

This will also cause the default action of the browser with the same name (if one exists) to be executed. For example, passing 'submit' to the trigger() function will also cause the browser to submit the form. This default action can be prevented by returning false from one of the functions bound to the event.

If a native event is triggered and a suitable event object is not passed as the first element of 'data', then a fake event object is added before all supplied 'data' arguments. This element contains appropriate 'type' and 'target' fields and null-op 'preventDefault' and 'stopPropagation' methods, but none of the clientXY/pageXY/keyCode fields specific to mouse and keyboard events. A "suitable" event object is judged by the presence of the 'preventDefault' field.

You can also trigger custom events registered with bind.

Arguments:
typeString
An event type to trigger.
data (Optional)Array
Additional data to pass as arguments (after the event object) to the event handler.

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

    $("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(), 0);
      j.text(n + 1);
    }

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    
    $("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(), 0);
      j.text(n + 1);
    }

  });
  </script>
  <style>
  button { margin:10px; }
  div { color:blue; font-weight:bold; }
  span { color:red; }
  </style>
</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>
</body>
</html>

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

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

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 too "foo" and b refers to "bar"
} ).trigger("click", ["foo", "bar"]);

This would display a "Hello World!" alert box.

$("p").bind("myEvent", function (event, message1, message2) {
  alert(message1 + ' ' + message2);
});
$("p").trigger("myEvent", ["Hello","World!"]);

NameType