Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Does adding an event listener overwrite the previous listener of the same event?

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"?

like image 436
trusktr Avatar asked Apr 23 '12 09:04

trusktr


People also ask

What happens if you add an event listener twice?

If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded.

Can you have multiple event listeners for the same event?

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.

Which jQuery function can be used to override events in 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.

Do event listeners only work once?

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.


2 Answers

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.

like image 68
wheresrhys Avatar answered Oct 07 '22 03:10

wheresrhys


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.

like image 31
T. Junghans Avatar answered Oct 07 '22 01:10

T. Junghans