jQuery listen globally for custom event

Will picture Will · Mar 20, 2012 · Viewed 17.8k times · Source

A simplified version of what i'm trying to do is as follows:

var indication = $('#some-div');
indication.bind('custom-event', function() { ... }


 // ... later on!

 function OtherThing() {
   $(this).trigger('custom-event');
 }

I'd like indication.bind('custom-event') to receive the trigger from function OtherThing without the two having to explicitly know about each other. Is this possible? My only solution so far is to bind both the listener and the event to body ... this seems sloppy -- is there a better way?

Answer

Rafael Verger picture Rafael Verger · Mar 20, 2012

In JavaScripts, the events triggered on each HTML Element are propagated to their parents, so, to solve your problem and make any element be capable to handle the custom event without do something wrong like $('*').bind('custom-event') is to bind the listener to a common parent for all elements, the body or html elements :]

So, you only need to bind the event to body or html element. Then, when any element, inside the choosen parent element, trigger the custom event, it will be propagated to this parent element.

And then, in the event handler, you can access the element that has triggered the event by accessing target attribute for the event object: event.target

So, the code should be:

$('body').bind('custom-event', function(e){
  var $element = e.target;
});

$('#anyElement').trigger('custom-event');