Reputation: 3674
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?
Upvotes: 1
Views: 6022
Reputation: 490193
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.
Upvotes: 7