I'm wondering how to use addEventListener
respectively attachEvent
correctly?
window.onload = function (myFunc1) { /* do something */ }
function myFunc2() { /* do something */ }
if (window.addEventListener) {
window.addEventListener('load', myFunc2, false);
} else if (window.attachEvent) {
window.attachEvent('onload', myFunc2);
}
// ...
or
function myFunc1() { /* do something */ }
if (window.addEventListener) {
window.addEventListener('load', myFunc1, false);
} else if (window.attachEvent) {
window.attachEvent('onload', myFunc1);
}
function myFunc2() { /* do something */ }
if (window.addEventListener) {
window.addEventListener('load', myFunc2, false);
} else if (window.attachEvent) {
window.attachEvent('onload', myFunc2);
}
// ...
?
Is this cross-browser secure or should I better go with something like this:
function myFunc1(){ /* do something */ }
function myFunc2(){ /* do something */ }
// ...
function addOnloadEvent(fnc){
if ( typeof window.addEventListener != "undefined" )
window.addEventListener( "load", fnc, false );
else if ( typeof window.attachEvent != "undefined" ) {
window.attachEvent( "onload", fnc );
}
else {
if ( window.onload != null ) {
var oldOnload = window.onload;
window.onload = function ( e ) {
oldOnload( e );
window[fnc]();
};
}
else
window.onload = fnc;
}
}
addOnloadEvent(myFunc1);
addOnloadEvent(myFunc2);
// ...
AND: Say myfunc2
is for IE 7 only. How to modify the correct/preferred method accordingly?
Anyone still hitting this discussion and not finding the answer they were looking for checkout:
http://dustindiaz.com/rock-solid-addevent
This is one of the most elegant solutions I found for those of us with restrictions on using the frameworks.
The usage of both is similar, though both take on a slightly different syntax for the event parameter:
addEventListener (mdn reference):
Events list for
addEventListener
.attachEvent (msdn reference):
Events list for
attachEvent
.Arguments
For both of the methods the arguments are as follows:
1. Is the event type.
2. Is the function to call once the event has been triggered.
3. (
addEventListener
only) If true, indicates that the user wishes to initiate capture.Explanation
Both methods are used to achieve the same goal of attaching an event to an element.
The difference being is that
attachEvent
can only be used on older trident rendering engines (IE5+IE5-8*) andaddEventListener
is a W3 standard that is implemented in the majority of other browsers (FF, Webkit, Opera, IE9+).For solid cross browser event support including normalizations that you won't get with the Diaz solution use a framework.
*IE9-10 support both methods, for backwards compatibility.
Thanks to Luke Puplett for pointing out that
attachEvent
has been removed from IE11.Minimal cross browser implementation
As Smitty recommended you should take a look at this Dustin Diaz addEvent for a solid cross browser implementation without the use of a framework: