The easiest and most robust way to do this is to use a library to do it for you, like Prototype, jQuery, Closure, etc. That way, you get the benefit of other people finding and reporting/fixing bugs rather than having to do it all yourself. :-)
But:
DOM elements have addEventListener
(and attachEvent
, on IE) on them as well, so it's fairly easy to create a general function for this:
function hook(obj, event, handler) {
if (obj.attachEvent) {
obj.attachEvent("on" + event, handler);
}
else if (obj.addEventListener) {
obj.addEventListener(event, handler);
}
else {
// Fail, probably
}
}
(Note that the IE variant uses "on" [e.g., "onclick"], the standard doesn't ["click"].)
It's a bit more efficient to test once and then use whichever the browser has, though:
var hook = (function() {
var elm = document.createElement('div');
if (elm.attachEvent)
{
return hookWithAttachEvent;
}
if (elm.addEventListener)
{
return hookWithAddEventListener;
}
return hookFail;
function hookWithAttachEvent(obj, event, handler) {
obj.attachEvent("on" + event, handler);
return obj;
}
function hookWithAddEventListener(obj, event, handler) {
obj.addEventListener(event, handler);
return obj;
}
function hookFail() {
throw "Don't know how to hook events on this platform.";
}
})();
That detects, once, which variant should be used and returns a function using that variant, which will then be called directly when you use hook
.