jQuery .triggerHandler() method

Syntax and Description

.triggerHandler(eventType[, extraParameters])
  • eventType is a string containing a JavaScript event type such as click or submit
  • extraParameters is an array of additional parameters to pass along to the event handler

Return value is the return value of the triggered handler, or undefined if no handlers are triggered.

The .triggerHandler() method executes all handlers attached to an element for an event. It does not cause the default behavior of an event to fire. .triggerHandler() only affects the first matched element.

Events created with .triggerHandler() do not bubble up the DOM hierarchy. It returns whatever value was returned by the last handler it caused to be executed. .triggerHandler() executes the attached handler rather than the native method.

Trigger click handler

The following code triggers the click event handler with triggerHandler method.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--  w ww.ja  va  2 s  . c  o  m-->
               $("h1").click(function () {
                  alert("h1");
               });
               $("button:last").click(function () {
                    $("h1").triggerHandler('click');
               });
        });
    </script>
  </head>
  <body>
    <body>
       <div><h1>header 1</h1></div>
       <button value="java2s.com">java2s.com</button>
    </body>
</html>

Click to view the demo

Trigger focus event handler

The following code triggers focus event handler.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--from w  w w . ja  va 2 s.  co m-->
            $("#old").click(function(){
              $("input").trigger("focus");
            });
            $("#new").click(function(){
              $("input").triggerHandler("focus");
            });
            $("input").focus(function(){
              $("<span>Focused!</span>").appendTo("body");
            });
        });
    </script>
  </head>
  <body>
    <body>
          <button id="old">.trigger("focus")</button>
          <button id="new">.triggerHandler("focus")</button><br/><br/>
          <input type="text" value="To Be Focused"/>
    </body>
</html>

Click to view the demo





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities