Reputation: 125
I have a lot of code that use addEventListener
in minified libraries, files ..., but I need to make work this code in IE8, so replacing addEventListener
with addEvent
:
/*
* Register the specified handler function to handle events of the specified
* type on the specified target. Ensure that the handler will always be
* invoked as a method of the target.
*/
function addEvent(type, handler) {
if (this.addEventListener)
this.addEventListener(type, handler, false);
else {
this.attachEvent("on" + type,
function(event) {
return handler.call(this, event);
});
}
}
I can "override" window.addEventListener
, but how can I override this method in the other objects?
Thanks in advance Regards
Upvotes: 4
Views: 7727
Reputation: 41675
To access it the same way as you would in modern browsers, you'll want to add the method to Window
, HTMLDocument
, and Element
prototypes.
(function(){
if (!("addEventListener" in window)) {
function addEventListener(type, handler) {
var _this = this;
this.attachEvent("on" + type, function(){
handler.call(_this, window.event);
});
}
Window.prototype.addEventListener = addEventListener;
HTMLDocument.prototype.addEventListener = addEventListener;
Element.prototype.addEventListener = addEventListener;
}
})();
Note: while we've normalized access to the function and addressed the this
issue, we haven't normalized the event to w3c standards. So, it will be missing properties like event.target
, event.relatedTarget
, etc.
Check out Mozilla's addEventListener()
shim.
Upvotes: 5