Skip to content

Instantly share code, notes, and snippets.

@overbalance
Forked from brunoais/addEventListener-polyfill.js
Last active December 21, 2015 08:09
Show Gist options
  • Save overbalance/6276343 to your computer and use it in GitHub Desktop.
Save overbalance/6276343 to your computer and use it in GitHub Desktop.
//addEventListener polyfill 1.0 / Eirik Backer / MIT Licence : Improved by brunoais
(function(win, doc) {
if (win.addEventListener) {
return;
}
//No need to polyfill
function docHijack(p) {
var old = doc[p];
doc[p] = function(v) {
return addListen(old(v));
};
}
function addEvent(on, fn, self) {
// There are events IE does not support. This will translate those to the best option available
switch (on) {
case "DOMContentLoaded":
on = "load";
break;
}
return (self = this).attachEvent("on" + on, function(e) {
e = e || win.event;
e.preventDefault = e.preventDefault || function() {
e.returnValue = false;
};
e.stopPropagation = e.stopPropagation || function() {
e.cancelBubble = true;
};
e.target = e.srcElement;
e.relatedTarget = e.toElement;
fn.call(self, e);
});
}
function addListen(obj, i) {
if (i = obj.length) {
while (i--) {
obj[i].addEventListener = addEvent;
}
} else {
obj.addEventListener = addEvent;
}
return obj;
}
addListen([ doc, win ]);
if ("Element" in win) {
// IE8
win.Element.prototype.addEventListener = addEvent;
} else {
// IE < 8
doc.attachEvent("onreadystatechange", function() {
addListen(doc.all);
});
// Make sure we also init at domReady
docHijack("getElementsByTagName");
docHijack("getElementById");
docHijack("createElement");
addListen(doc.all);
}
})(window, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment