Rakesh Juyal
Rakesh Juyal

Reputation: 36749

Why is this javascript not working?

This is in continuation of the question:

innerHTML working in FF but not in IE!

The above problem is resolved [ thanx to pygorex1 ] . But i would like to know why the following code snippet is not working.

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

function loadNewElements(){
    document.createElement("showDateFormat");
}

function addDateFormatInfo(){
    var dateFormatHolder = document.getElementsByTagName("showDateFormat");     
    if ( dateFormatHolder ){            
        for ( i = 0 ; i < dateFormatHolder.length; i++ ){
                dateFormatHolder[i].innerHTML = '<div class="infoSmall" ><span>(mm/dd/yyyy)</span></div>';                                               
        } 
    }
}

provided it is working in FF but not in IE
also, if instead of creating a new method loadNewElements and attaching this to load the event if i will directly write document.createElement("showDateFormat"); in my javascript [ not in any method ], then the code works as expected [ both in IE and FF ]. Why it is so?

Upvotes: -1

Views: 946

Answers (2)

Mr. Shiny and New 安宇
Mr. Shiny and New 安宇

Reputation: 13908

I'd try doing this:

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

Upvotes: 2

Fabien M&#233;nager
Fabien M&#233;nager

Reputation: 140195

You need to call loadNewElements before the other method.

If it doesn't work, write like this :

if (window.addEventListener){   
    window.addEventListener('load', addDateFormatInfo, false);  
    //window.addEventListener('load', loadNewElements, false);    // Don't need this for non-IE browsers
} else if (window.attachEvent){ 
    loadNewElements(); // Will always be executed before the other one
    window.attachEvent('onload', addDateFormatInfo);    
}

Upvotes: 3

Related Questions