Firefox / IE JavaScript compatibility

The ever-excellent Dare Obasanjo posted a comment yesterday about event compatibility between IE and Mozilla. Basically, IE uses a function called attachEvent to add an event to an element dynamically, but FF et al use the W3C-specifed addEventListener.
Luckily, Mozilla supports a really great system for extending object prototypes so you can roll your own attachEvent function and use that syntax exclusively rather than wrapping everything in a "if (window.addEventListener)" block.
Something like this should work. It won’t create 100% compatibility but you’re well on the way.
if (window.addEventListener)
   window.attachEvent =
   HTMLDocument.prototype.attachEvent =
   HTMLElement.prototype.attachEvent =
   function(name, handler) {
      this.addEventListener(name.slice(2), handler, true);
   window.removeEvent =
   HTMLDocument.prototype.removeEvent =
   HTMLElement.prototype.removeEvent =
   function(name, handler) {
      this.removeEventListener(name.slice(2), handler, true);

In my own systems I use a rather more complex version that deals rather better with mouse events, but it’s a bit much code to put in here.
On another note, surely the reverse of "attachEvent" should be "detachEvent", not "removeEvent"?
This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s