jQuery Custom Events

2009-11-14 00:00:00 +0000 by Alex R. Young

jQuery makes it easy to bind and trigger custom events. Although it's
not immediately apparent from the
, creating custom
events is simple and very useful.

Binding Custom Events

Events can be bound to DOM nodes like this:

$("#myElementId").bind("myCustomEvent", function(event) {
  alert("myCustom event happened!");

Triggering Custom Events

jQuery's trigger function is
used to instigate the event, passing the name of the event as a string
like this:


If you want to pass data to the handler you can use an event

var myCustomEvent = jQuery.Event("myCustomEvent");
myCustomEvent.usefulInformation = "some data";
myCustomEvent.otherStuff = "some other data";


Another cool feature of jQuery events is
namespacing, which supports triggering or unbinding specific groups of handlers without having to
reference them directly.

You can add a namespace when binding an event which can be referenced
when you unbind or trigger it. It's possible to use multiple namespaces
at once.

$('.myCSSClass').bind('myEvent.myNamespace.myOtherNamespace', function(){alert('namespaced event')});

If you specify a namespace when unbinding or triggering events, you need
to match one of the bound namespaces (or alternatively, if no namespace
is specified it matches everything).

$('.myCSSClass').bind('myEvent.myNamespace', function(){alert('namespaced event')});
$('.myCSSClass').trigger('myEvent.myNamespace'); // mentioned explicitly: will trigger
$('.myCSSClass').trigger('myEvent');  // not specified: will trigger
$('.myCSSClass').unbind('myEvent.differentNamespace'); // won't unbind