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); }
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.
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.
If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded.
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);
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