In JavaScripts, the events triggered by each HTML element are propagated to their parents, therefore, to solve your problem and make any element capable of handling a custom event without doing something different from $('*').bind('custom-event')
to associate the listener with a common parent for all elements, body
or html
elements:]
So, you need to bind the event only to the body
or html
element. Then, when any element inside the selected parent element fires a custom event, it will be propagated to this parent element.
And then in the event handler you can access the element that raised the event by accessing the 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');
source share