1

This code works nicely in for example Chrome, but not in Internet Explorer 8/9.

/* sitepoint.com/javascript-this-event-handlers */ function AttachEvent(element, type, handler){if (element.addEventListener){element.addEventListener(type, handler, false);}else{element.attachEvent("on"+type, handler);}} window.addEventListener("load", function() { //do some stuff AttachEvent(id, "click", function_name); }, false); 

IE already complains about the addEventListener line. I believe I need to use attachEvent instead. How do I do this? I would prefer to keep the code that is working in the other browsers and only use attachEvent in Internet Explorer. How do I get this cross-browser compatible?

1
  • This is where JS libraries such as jQuery shine. Commented Mar 16, 2012 at 19:09

1 Answer 1

7

IE9 does support addEventListener().

Here is how your existing function would work with attachEvent (and the old on* property).

// logic to attach the event correctly in IE9 function AttachEvent(element, type, handler) { if (element.addEventListener) { element.addEventListener(type, handler, false); }else if (element.attachEvent) { element.attachEvent('on' + type, handler) } else { element['on' + type] = handler; } } 

You'd then set the window load event...

AttachEvent(window, "load", function() { // ... }); 

Don't forget that the event is global with the older IEs. You could script around that if you wanted to. You'd simply have each function call this callback() which would go on to invoke the user-supplied handler() with the correct arguments.

var callback = function(e) { e = e || window.event; handler.call(element, e); }; 

You could get carried away and try and normalise properties on event, such as target/srcElement, but then you might want to consider an existing library.

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

1 Comment

Ah, okay, yes. I can just reused that function, good idea. I will try it out.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.