Custom jQuery Events

Custom events are an underappreciated feature of jQuery that make it easy to graft a powerful distributed event system onto any web app, with no additional libraries. You can emit any event you want from any DOM element from jQuery using trigger.

​ 
$(​'#tabby, #socks'​).on(​'meow'​, ​function​() {
​ 
console.log(this.id + ​' meowed'​);
​ 
});
​ 
$(​'#tabby'​).trigger(​'meow'​); ​// "tabby meowed"​
​ 
$(​'#socks'​).trigger(​'meow'​); ​// "socks meowed"​

If you’ve worked with DOM events before, you’re no doubt familiar with bubbling. Whenever an element emits an event (such as a ’click’), its parent then emits the event, then its grandparent, and so on, up to the root ...

Get Async JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.