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?
IE9 does support
addEventListener().Here is how your existing function would work with
attachEvent(and the oldon*property).You’d then set the window load event…
Don’t forget that the
eventis global with the older IEs. You could script around that if you wanted to. You’d simply have each function call thiscallback()which would go on to invoke the user-suppliedhandler()with the correct arguments.You could get carried away and try and normalise properties on
event, such astarget/srcElement, but then you might want to consider an existing library.