Skip to content

Instantly share code, notes, and snippets.

@jonathantneal
Created June 4, 2012 16:27
Show Gist options
  • Select an option

  • Save jonathantneal/2869388 to your computer and use it in GitHub Desktop.

Select an option

Save jonathantneal/2869388 to your computer and use it in GitHub Desktop.
Event Listener polyfill
// addEventListener polyfill IE6+
!window.addEventListener && (function (window, document) {
function Event(e, element) {
var 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;
};
}
function addEventListener(type, listener) {
var
element = this,
listeners = element.listeners = element.listeners || [],
index = listeners.push([listener, function (e) {
listener.call(element, new Event(e, element));
}]) - 1;
element.attachEvent('on' + type, listeners[index][1]);
}
function removeEventListener(type, listener) {
for (var element = this, listeners = element.listeners || [], length = listeners.length, index = 0; index < length; ++index) {
if (listeners[index][0] === listener) {
element.detachEvent('on' + type, listeners[index][1]);
}
}
}
window.addEventListener = document.addEventListener = addEventListener;
window.removeEventListener = document.removeEventListener = removeEventListener;
if ('Element' in window) {
Element.prototype.addEventListener = addEventListener;
Element.prototype.removeEventListener = removeEventListener;
} else {
var
head = document.getElementsByTagName('head')[0],
style = document.createElement('style');
head.insertBefore(style, head.firstChild);
style.styleSheet.cssText = '*{-ms-event-prototype:expression(!this.addEventListener&&(this.addEventListener=addEventListener)&&(this.removeEventListener=removeEventListener))}';
}
})(window, document) && scrollBy(0, 0);
@carlosascari

Copy link
Copy Markdown

Keep in mind, for...in loops are supported by IE10+. So this polyfill will not work unless you replace then with normal for(;;) loops.

@paulyn000

Copy link
Copy Markdown

will this work on DOMContentLoaded, readystatechange, progress or what?

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