jQuery Custom Events

January 18th, 2012
By: Cory Mathews

We are used to javascript events such as a “click” being handled similar to the following:

$('#id').on("click", function() {
    alert("Item clicked");
});

But less common is the use of custom events available with the .trigger() and .triggerHandler() jQuery functions. With this I could create an event such as “cory.says.hello”, if I so wished and then handle it with

$('#id').on("cory.says.hello", function() {
    alert("Hello Cory");
});

Usage

So you are writting a lightbox plugin (or whatever plugin really), and you want to give anyone the ability to add additional logic when the lightbox opens. Of the many ways to allow them to do this an easy way is to create a custom event for them to handle.

So continuing with the lightbox example, you could add an event when you open the lightbox with something like:

function open() {
  //blah
  $('#id')triggerHandler({ type:"lightbox.open" });
  //more
}

which could then later be caught by anyone using your plugin like so:

$(function() {
  $('#id').on("lightbox.open", function() {
    alert("The lightbox just opened. Woo!");
  });
});

Nice and simplistic. What about passing variables to the event handler? Maybe I want to run an event on an ajax response or whatever the case may be.

  $('#id').triggerHandler({ 
    type:"lightbox.open",
    var1:'Howdy',
    information:'I could pass something here also'
  });

Then to get the var1, and information data out of the previous example we would do:

$(function() {
  $('#id').on("lightbox.open", function(o) {
    alert(o.var1 + " - " + o.information);
  });
});

Differences between .trigger() and .triggerHandler()

The differences between the two are pretty small, but still important. To quote the jQuery Docs:

The .triggerHandler() method behaves similarly to .trigger(), with the following exceptions:

  • The .triggerHandler() method does not cause the default behavior of an event to occur (such as a form submission).
  • While .trigger() will operate on all elements matched by the jQuery object, .triggerHandler() only affects the first matched element.
  • Events created with .triggerHandler() do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.
  • Instead of returning the jQuery object (to allow chaining), .triggerHandler() returns whatever value was returned by the last handler it caused to be executed. If no handlers are triggered, it returns undefined