Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can multiple event listeners/handlers be added to the same element using Javascript?

I have:

if (window.addEventListener) {   window.addEventListener('load',videoPlayer,false); } else if (window.attachEvent) {    window.attachEvent('onload',videoPlayer); } 

and then later I have:

if (window.addEventListener) {   window.addEventListener('load',somethingelse,false); } else if (window.attachEvent) {    window.attachEvent('onload',somethingelse); } 

Is it preferred/functional to have them all together? Like

if (window.addEventListener) {   window.addEventListener('load',videoPlayer,false);   window.addEventListener('load',somethingelse,false); } else if (window.attachEvent) {    window.attachEvent('onload',videoPlayer,false);   window.attachEvent('onload',somethingelse); } 
like image 806
bryan sammon Avatar asked Mar 23 '11 20:03

bryan sammon


People also ask

Can I add multiple event listeners for the same event?

We can add multiple event listeners for different events on the same element. One will not replace or overwrite another. In the example above we add two extra events to the 'button' element, mouseover and mouseout.

Can we register more than one event handler for an element using addEventListener method?

You can assign as many handlers as you want to an event using addEventListener(). addEventListener() works in any web browser that supports DOM Level 2.

What happens if you add event listener twice?

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


1 Answers

You can do how ever you want it to do. They don't have to be together, it depends on the context of the code. Of course, if you can put them together, then you should, as this probably makes the structure of your code more clear (in the sense of "now we are adding all the event handlers").

But sometimes you have to add event listeners dynamically. However, it is unnecessary to test multiple times whether you are dealing with IE or not.

Better would be to abstract from this and test only once which method is available when the page is loaded. Something like this:

var addEventListener = (function() {     if(document.addEventListener) {         return function(element, event, handler) {             element.addEventListener(event, handler, false);         };     }     else {         return function(element, event, handler) {             element.attachEvent('on' + event, handler);         };     } }()); 

This will test once which method to use. Then you can attach events throughout your script with:

addEventListener(window, 'load',videoPlayer); addEventListener(window, 'load',somethingelse); 
like image 100
Felix Kling Avatar answered Sep 20 '22 12:09

Felix Kling