addEventListener in Internet Explorer

The Mask picture The Mask · Aug 3, 2011 · Viewed 109.7k times · Source

What is the equivalent to the Element Object in Internet Explorer 9?

if (!Element.prototype.addEventListener) {
    Element.prototype.addEventListener = function() { .. } 
} 

How does it works in Internet Explorer?

If there's a function equal to addEventListener and I don't know, explain please.

Any help would be appreciated. Feel free to suggest a completely different way of solving the problem.

Answer

user278064 picture user278064 · Aug 3, 2011

addEventListener is the proper DOM method to use for attaching event handlers.

Internet Explorer (up to version 8) used an alternate attachEvent method.

Internet Explorer 9 supports the proper addEventListener method.

The following should be an attempt to write a cross-browser addEvent function.

function addEvent(evnt, elem, func) {
   if (elem.addEventListener)  // W3C DOM
      elem.addEventListener(evnt,func,false);
   else if (elem.attachEvent) { // IE DOM
      elem.attachEvent("on"+evnt, func);
   }
   else { // No much to do
      elem["on"+evnt] = func;
   }
}