jQuery

jQuery Trigger Example

The aim of this example is to introduce and see cases of .trigger() method of jQuery. The trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements. This method is similar to the triggerHandler() method, except that triggerHandler() does not trigger the default behavior of the event.

Several jQuery plugins use .trigger() method to to notify other sections of code that an application specific event has happened. Below, we’ll have a look at an example of its usage and then give some more information on handlers that can be triggered and why you should use an alternative method like triggerHandler() for security reasons.
 

1. Basic Document Setup

To begin, create a new HTML document, and add the following basic syntax:

<!DOCTYPE html>
<html>
<head>
	<title>jQuery Trigger Example</title>
</head>
<body>
<!-- STYLE SECTION  -->
<style type="text/css">

</style>

<!-- HTML SECTION  -->

<!-- JAVASCRIPT SECTION  -->
<script src="jquery-1.11.3.min.js"></script>

<script type="text/javascript">

</script>

</body>
</html>

Note that jQuery library is included as a local file here, you might consider downloading it from the official website here.

2. Method Application and Notes

Below, let’s take into consideration an example of the usage of .trigger() and then talk about what else it can do.

2.1 .trigger() Application

To apply the method, first add two elements, div and a button. We’ll use the button to trigger a function to the div.

<!-- HTML SECTION  -->
<button>Click Me</button>
<div>I am </div>

Next, in the JS section first select the div tag and append some text to it on the click handler. Then, on button click, trigger the click event so that text append happens.

<!-- JAVASCRIPT SECTION  -->
<script type="text/javascript">
$(document).ready(function(){
    $('div').on('click', function(){
        $('div').append('someone, ');

    });
    $('button').click(function(){
        $('div').trigger('click')
    });
});
</script>

The result in the browser would be as follows:
trigger1

2.2 What handlers can be .trigger()’d?

jQuery’s event handling system is a layer on top of native browser events. When an event handler is added using .on( "click", function() {...} ), it can be triggered using jQuery’s .trigger( "click" ) because jQuery stores a reference to that handler when it is originally added.

Additionally, it will trigger the JavaScript inside the onclick attribute. The .trigger() function cannot be used to mimic native browser events, such as clicking on a file input box or an anchor tag. This is because, there is no event handler attached using jQuery’s event system that corresponds to these events.

2.3 .trigger() vs .triggerHandler()

There are four differences between .trigger() and .triggerHandler():

1. .triggerHandler() only triggers the event on the first element of a jQuery object.

2. .triggerHandler() cannot be chained. It returns the value that is returned by the last handler, not a jQuery object.

3. .triggerHandler() will not cause the default behavior of the event (such as a form submission).

4. Events triggered by .triggerHandler(), will not bubble up the DOM hierarchy. Only the handlers on the single element will fire.

2.4 Not Recommended Simply to Execute Specific Functions

While this method has its uses, it should not be used simply to call a function that was bound as a click handler. Instead, you should store the function you want to call in a variable, and pass the variable name when you do your binding. Then, you can call the function itself whenever you want, without the need for .trigger().

<!-- JAVASCRIPT SECTION  -->
<script type="text/javascript">
// Triggering an event handler the right way
var foo = function( event ) {
    if ( event ) {
        console.log( event );
    } else {
        console.log( "This didn't come from an event!" );
    }
};
$( "p" ).on( "click", foo );
foo(); // instead of $( "p" ).trigger( "click" )
</script>

The result would be identically the same.

2.5 Pass Arbitrary Data To and Thorugh an Event Object

To pass arbitrary data to an event you can do like so:

<!-- JAVASCRIPT SECTION  -->
<script type="text/javascript">
$( "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" ] );
</script>

To pass arbitrary data through an event object:

<!-- JAVASCRIPT SECTION  -->
<script type="text/javascript">
var event = jQuery.Event( "logged" );
event.user = "foo";
event.pass = "bar";
$( "body" ).trigger( event );
</script>

or use this alternative way:

<!-- JAVASCRIPT SECTION  -->
<script type="text/javascript">
$( "body" ).trigger({
  type:"logged",
  user:"foo",
  pass:"bar"
});
</script>

3. Conclusion

To conclude, .trigger() is a rather specific-case method, and not used a lot. The .triggerHandler() method is jQuery’s way of preventing the problems that trigger can create. Basically, the method will execute all handlers and behaviors attached to the matched elements for the given event type. Well, the word is self-explanatory, trigger.

4. Download

Download
You can download the full source code of this example here: jQuery Trigger

Fabio Cimo

Fabio is a passionate student in web tehnologies including front-end (HTML/CSS) and web design. He likes exploring as much as possible about the world wide web and how it can be more productive for us all. Currently he studies Computer Engineering, at the same time he works as a freelancer on both web programming and graphic design.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button