addEventListener in Internet Explorer
Asked Answered
R

8

70

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.

Raman answered 3/8, 2011 at 13:57 Comment(1)
Whether a browser implements a prototype inheritance scheme for its DOM objects is not relevant to whether it supports the W3C EventTarget interface. If you wish to test for support, test it directly: if(element.addEventListener) {/*supported*/} else {/*not supported*/} is effective in all browsers and is independent of the implementation.Serranid
M
149

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;
   }
}
Merow answered 3/8, 2011 at 14:7 Comment(4)
The last condition should also include "on"+.Petree
For IE9 and addEventListener you need an HTML5 <!DOCTYPE html>Fixation
@Fixation wish I could up vote that comment more. Very important pointChymotrypsin
Also since IE9 uses IE7 rendering mode in Compatibility view, only the attachEvent works. So it is important to have this check instead of relying on addEventListener.Sheritasherj
P
16

John Resig, author of jQuery, submitted his version of cross-browser implementation of addEvent and removeEvent to circumvent compatibility issues with IE's improper or non-existent addEventListener.

function addEvent( obj, type, fn ) {
  if ( obj.attachEvent ) {
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
    obj.attachEvent( 'on'+type, obj[type+fn] );
  } else
    obj.addEventListener( type, fn, false );
}
function removeEvent( obj, type, fn ) {
  if ( obj.detachEvent ) {
    obj.detachEvent( 'on'+type, obj[type+fn] );
    obj[type+fn] = null;
  } else
    obj.removeEventListener( type, fn, false );
}

Source: http://ejohn.org/projects/flexible-javascript-events/

Predatory answered 17/6, 2014 at 5:53 Comment(3)
This code tries to bind callback fn to obj in addition to adding an event listener, but this is redundant because everyone using JS should already know about this.Anastigmatic
You would've gotten more votes if you had introduced John Resig as the author of jQuery.Cheshire
This implementation isn't complete. It's missing the useCapture parameter.Hibbitts
N
14

I'm using this solution and works in IE8 or greater.

if (typeof Element.prototype.addEventListener === 'undefined') {
    Element.prototype.addEventListener = function (e, callback) {
      e = 'on' + e;
      return this.attachEvent(e, callback);
    };
  }

And then:

<button class="click-me">Say Hello</button>

<script>
  document.querySelectorAll('.click-me')[0].addEventListener('click', function () {
    console.log('Hello');
  });
</script>

This will work both IE8 and Chrome, Firefox, etc.

Nakasuji answered 4/9, 2014 at 20:49 Comment(2)
I have problem with Element (type is undefined)Samphire
check your document type version, this should be html5 doctypeNakasuji
T
2

As Delan said, you want to use a combination of addEventListener for newer versions, and attachEvent for older ones.

You'll find more information about event listeners on MDN. (Note there are some caveats with the value of 'this' in your listener).

You can also use a framework like jQuery to abstract the event handling altogether.

$("#someelementid").bind("click", function (event) {
   // etc... $(this) is whetver caused the event
});
Taegu answered 3/8, 2011 at 14:4 Comment(0)
S
2

Here's something for those who like beautiful code.

function addEventListener(obj,evt,func){
    if ('addEventListener' in window){
        obj.addEventListener(evt,func, false);
    } else if ('attachEvent' in window){//IE
        obj.attachEvent('on'+evt,func);
    }
}

Shamelessly stolen from Iframe-Resizer.

Souterrain answered 11/1, 2016 at 19:55 Comment(0)
T
1

addEventListener is supported from version 9 onwards; for older versions use the somewhat similar attachEvent function.

Thirtythree answered 3/8, 2011 at 13:58 Comment(0)
C
1

EDIT

I wrote a snippet that emulate the EventListener interface and the ie8 one, is callable even on plain objects: https://github.com/antcolag/iEventListener/blob/master/iEventListener.js

OLD ANSWER

this is a way for emulate addEventListener or attachEvent on browsers that don't support one of those
hope will help

(function (w,d) {  // 
    var
        nc  = "", nu    = "", nr    = "", t,
        a   = "addEventListener",
        n   = a in w,
        c   = (nc = "Event")+(n?(nc+= "", "Listener") : (nc+="Listener","") ),
        u   = n?(nu = "attach", "add"):(nu = "add","attach"),
        r   = n?(nr = "detach","remove"):(nr = "remove","detach")
/*
 * the evtf function, when invoked, return "attach" or "detach" "Event" functions if we are on a new browser, otherwise add "add" or "remove" "EventListener"
 */
    function evtf(whoe){return function(evnt,func,capt){return this[whoe]((n?((t = evnt.split("on"))[1] || t[0]) : ("on"+evnt)),func, (!n && capt? (whoe.indexOf("detach") < 0 ? this.setCapture() : this.removeCapture() ) : capt  ))}}
    w[nu + nc] = Element.prototype[nu + nc] = document[nu + nc] = evtf(u+c) // (add | attach)Event[Listener]
    w[nr + nc] = Element.prototype[nr + nc] = document[nr + nc] = evtf(r+c) // (remove | detach)Event[Listener]

})(window, document)
Crewel answered 23/1, 2015 at 23:6 Comment(0)
R
0

I would use these polyfill https://github.com/WebReflection/ie8

<!--[if IE 8]><script
  src="//cdnjs.cloudflare.com/ajax/libs/ie8/0.2.6/ie8.js"
></script><![endif]-->
Restrained answered 3/8, 2015 at 22:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.