It's not so hard actually - there isn't so many event definitions, only three versions. The first one is the corect one (addEventListener
), then there's the IE way (attachEvent
) and then there's the compatibility way for older browser (element.onevent = function
)
So a complete event handling solution would look something like this:
setEvent = function(element, eventName, handler){
if('addEventListener' in element){
//W3
element.addEventListener(eventName,handler,false);
}else if('attachEvent' in elm){
//IE
elm.attachEvent('on'+eventName,handler)
}else{
// compatibility
elm['on'+eventName] = handler;
}
}
and to clear events:
clearEvent = function(element, eventName, handler){
if('removeEventListener' in element){
//W3
element.removeEventListener(eventName,handler,false);
}else if('detachEvent' in elm){
//IE
elm.detachEvent('on'+eventName,handler)
}else{
// compatibility
elm['on'+eventName] = null;
}
}
and an example:
setEvent(document, "click", function(){alert('hello world!');});
clearEvent(document, "click", function(){alert('hello world!');});
This is not really a complete example though since the compatibility handler always overwrites the previous events (it's not appending actions, it's overwriting) so you probably would like to check if a handler is already set and then save it into some temporary variable and fire it inside the event handler function.