4

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

4
  • you can define window.addEventListener in IE to work as the W3 one, so that all code uses the same code, and new browsers use the native command instead of forking each time. Commented Oct 13, 2014 at 19:57
  • window.addEventListener = window.addEventListener || function addEvent(type, handler) { this.attachEvent("on" + type, function (event) { return handler.call(this, event); }); } Commented Oct 13, 2014 at 19:59
  • if i use above code only add addEventListener to window? I need to all objects Commented Oct 13, 2014 at 20:17
  • yeah, the above is just for window. you should use Object.defineProperty to do the same type of thing on Element.prototype (only for IE!). Commented Oct 13, 2014 at 20:48

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

you can modify protos to behave like other browsers without the risk that stems from creating your own brand-new property names waiting to conflict one day. since that name is already taken, you don't have to worry. IE8 supporte Object.defineProperty on Element protos (it's about the only place it actually works), so you can also avoid the pesky "you broke my for-in" complaints that have long been associated with modifying native object prototypes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.