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?
bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to . bind() occurs.
Projects In JavaScript & JQuery Use the off() method to override jQuery event handlers. This method is used to remove an event handler. The on() method is used to attach one or more event handler.
To trigger the onclick function in jQuery, click() method is used. For example, on clicking a paragraph on a document, a click event will be triggered by the $(“p”). click() method. The user can attach a function to a click method whenever an event of a click occurs to run the function.
jQuery error() Method The error() method triggers the error event, or attaches a function to run when an error event occurs.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With