Correct usage of addEventListener() /attachEvent()?

Posted by ginny on Stack Overflow See other posts from Stack Overflow or by ginny
Published on 2010-04-17T04:05:47Z Indexed on 2010/04/17 4:13 UTC
Read the original article Hit count: 346

Hi guys! I'm wondering how to use "addEventListener" resp. "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 sth. 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?

Thank you so much!

© Stack Overflow or respective owner

Related posts about addeventlistener

Related posts about attachevent