Skip to content Skip to sidebar Skip to footer

Addeventlistener Doesn't Work In Ie (tested In Ie8)

Work in Chrome and Firefox but not in IE. Fiddle I have tried solution from here but doesn't help. if(window.attachEvent){ // Attach event code here window.attachEve

Solution 1:

In IE, the event name is "onload", in W3C compliant browsers it's "load", so:

if (window.addEventListener) {
  window.addEventListener('load', ...);

} elseif (window.attachEvent) {
  window.attachEvent('onload', ...);
}

A better function for adding listeners in IE8 is below. It sets this to the element and passes event as the first parameter when using attachEvent to be more like addEventListener. It's not a full replacement for addEventListener, but there's an attempt at one on MDN. I'm not endorsing the function there (I think it will fail miserably in IE 7 and lower), just pointing it out as there is some good information in the article.

functionaddListener(element, event, fn) {

    // Use addEventListener if availableif (element.addEventListener) {
      element.addEventListener(event, fn, false);

    // Otherwise use attachEvent, set this and event
    } elseif (element.attachEvent) {
      element.attachEvent('on' + event, (function (el) {
        returnfunction() {
          fn.call(el, window.event);
        };
      }(element)));

      // Break closure and primary circular reference to element
      element = null;
    }
  }

Solution 2:

It's always a good idea to do a little research first. W3Schools (http://www.w3schools.com/jsref/dom_obj_event.asp) clearly gives the answer:

Allows the registration of event listeners on the event target (IE8 = attachEvent())

For knowing which one to use, just use a simple if statement

if(obj.attachEvent){
    // Attach event code here
}
else{
    // Addeventlistener code here
}

Post a Comment for "Addeventlistener Doesn't Work In Ie (tested In Ie8)"