For example, let's say I have
$(element).on('click', function() {/*Some Stuff*/});
defined somewhere, then later I want to add more features to that same click event. If I do
$(element).on('click', function() {/*Other Stuff*/});
will "Other Stuff" overwrite "Some Stuff"?
If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded.
You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements.
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.
Using the once option We can pass an object as an argument to the addEventListener method and specify that the event is only handled once. This is achieved by passing the property once to the object. If we set once to true, the event will only be fired once.
The second listener won't override the first. jQuery event handlers are added cumulatively and execute in the order they were attached.
The thing that does effect whether one handler prevents the other running is how the function cancels the browser's default click handler (i.e. how you stop the browser following the link's url)
If you use traditional method:
$(element).on('click', function() { /* Some Stuff, do your thing */ return false; });
The handler above will stop the event itself and propagating to other handlers.
But you can stop the event action without stopping its propagation or the handler:
$(element).on('click', function(e) { // prevent the default action at first, just to make it clear :) e.preventDefault(); /* do your thing */ return /* what you want */; });
This will ensure that the default click action doesn't occur but that the event continues to other hanlders. jQuery event also has some other useful event propagation methods (e.g. Event.stopPropagation()
) which are worth getting to know.
No, the events are not overwritten, they are appended or pushed to the list of event handlers.
This is a typical usage of the observer pattern.
Events can be removed with http://api.jquery.com/off/ or http://api.jquery.com/die/ in case .live
was used.
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