Skip to content

Instantly share code, notes, and snippets.

@Rich-Harris
Forked from jonathantneal/eventListener.js
Last active May 6, 2024 10:26
Show Gist options
  • Save Rich-Harris/6010282 to your computer and use it in GitHub Desktop.
Save Rich-Harris/6010282 to your computer and use it in GitHub Desktop.
// addEventListener polyfill IE6+
if ( !window.addEventListener ) {
(function ( win, doc ) {
var Event, addEventListener, removeEventListener, head, style;
Event = function ( e, element ) {
var property, instance = this;
for ( property in e ) {
instance[ property ] = e[ property ];
}
instance.currentTarget = element;
instance.target = e.srcElement || element;
instance.timeStamp = +new Date();
instance.preventDefault = function () {
e.returnValue = false;
};
instance.stopPropagation = function () {
e.cancelBubble = true;
};
};
addEventListener = function ( type, listener ) {
var element = this, listeners, i;
listeners = element.listeners || ( element.listeners = [] );
i = listeners.length;
listeners[i] = [ listener, function (e) {
listener.call( element, new Event( e, element ) );
}];
element.attachEvent( 'on' + type, listeners[i][1] );
};
removeEventListener = function ( type, listener ) {
var element = this, listeners, len, index;
if ( !element.listeners ) {
return;
}
listeners = element.listeners;
i = listeners.length;
while ( i-- ) {
if (listeners[i][0] === listener) {
element.detachEvent( 'on' + type, listeners[i][1] );
}
}
};
win.addEventListener = doc.addEventListener = addEventListener;
win.removeEventListener = doc.removeEventListener = removeEventListener;
if ( 'Element' in win ) {
Element.prototype.addEventListener = addEventListener;
Element.prototype.removeEventListener = removeEventListener;
} else {
head = doc.getElementsByTagName('head')[0];
style = doc.createElement('style');
head.insertBefore( style, head.firstChild );
style.styleSheet.cssText = '*{-ms-event-prototype:expression(!this.addEventListener&&(this.addEventListener=addEventListener)&&(this.removeEventListener=removeEventListener))}';
}
}( window, document ));
}
@brtubb
Copy link

brtubb commented Sep 8, 2015

Same error as the other two - exceptions on call. Likewise failing in IE8 via Browserstack, although the debug information isn't as verbose.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment