This content was originally published at Kyan’s blog at http://kyan.com/blog/2013/10/1/two-jquery-event-tricks, but is no longer available at that location. Reproduced here with permission.

Two jQuery event tricks

Everyone knows how to bind events in jQuery right?

$('a').on('click',function(){…});

Easy! There are a couple of nice extras though that are worth pointing out.

Binding to multiple events

jQuery will happy take a space separated string of event names instead of the one event. Why would you want to do this? Well, we recently built a site with functionality to trigger an animation as it scrolled into view:

$(window).on('scroll',function(){
	// check scroll and trigger animation
});

Once we added media queries we realised the element to be animated could appear if the page was resized without a scroll event being triggered. All we needed to do was add the resize event to the same handler binding.

$(window).on('scroll resize',function(){
	// check scroll and trigger animation
});

Be careful while unbinding

Let’s take the previous example a step further. With out animation we only want to to trigger once when it first appears. The obvious solution would be something like this:

$(window).on('scroll resize',function(){
	// check scroll
	$(window).off('scroll resize');
	// trigger animation
});

This works, but at a cost: it removes all other scroll and resize events bound to window by any of your plugins. This obviously could cause some fairly major problems. Luckily, jQuery provides for just this situation. It’s possible to namespace your events simply by adding a .namespace to the end of each. Once namespaced you can selectively turn them off by passing the namepace into $.off(). Even more helpfully we can turn off an entire namespace simply by omitting the event name:

$(window).on('scroll.myPlugin resize.myPlugin',function(){
	// check scroll
	$(window).off('.myPlugin');
	// trigger animation
});

These couple of features deserve more use as they both reduce the amount of code you have to write and make it less likely to interfere with the rest of your system.