javascriptaddeventlistenerattachevent

If/else with Event Listeners beginner JavaScript


I read that attach.event is only used in early versions of IE. I was wondering why it is used here, it seems to correspond to executing the populateFigures() part of the setUpPage() function, is this correct? I really appreciate any help!

function setUpPage() {
createEventListeners();
populateFigures();

}//end of setUpPage Function


/* run setUpPage() function when page finishes loading */

if (window.addEventListener) {
      window.addEventListener("load", setUpPage, false); 
} else if (window.attachEvent)  {
      window.attachEvent("onload", setUpPage);
}//end of else if

Solution

  • Yes this is correct.

    It is just to make sure that onload should work in IE (6 to 10) becuase of limited support of addEventListener in these versions of IE.

    attachEvent is a proprietary Microsoft Internet Explorer alternative to the standard EventTarget.addEventListener() method.

    So your code is checking if property addEventListener is present in the window object then add an event using addEventListener otherwise if the property attachEvent exists (primarily on IEs) on window object then add event using addEventListener.

    Read more about attachEvent here.