While waiting for the next release of Internet Explorer, which promises to normalize the W3C DOM event model, developers are forced to deal with the different implementations of event handling across browsers. One of the first developers who took care of this problem was actually Scott Andrew back in 2001. In his seminal article on the subject, Scott proposed two simple functions that normalize events across browser, thus allowing developers to attach event handlers without worrying about browser incompatibilities. These functions are the following:
function addEvent(obj, evType, fn, useCapture){ if (obj.addEventListener){ obj.addEventListener(evType, fn, useCapture); return true; } else if (obj.attachEvent){ var r = obj.attachEvent("on"+evType, fn); return r; } else { alert("Handler could not be attached"); } } function removeEvent(obj, evType, fn, useCapture){ if (obj.removeEventListener){ obj.removeEventListener(evType, fn, useCapture); return true; } else if (obj.detachEvent){ var r = obj.detachEvent("on"+evType, fn); return r; } else { alert("Handler could not be removed"); } }
W3C DOM compliant browsers use add
/removeEventListener
, whereas IE implements
attach
/detachEvent
. Both functions take care of this. A simple test:
var test = document.getElementById('test'); var enlarge = document.getElementById('enlarge'); function makeLarger(evt) { evt = event || window.event; test.style.width = '200px'; test.style.height = '200px'; if(evt.preventDefault) { evt.preventDefault(); } else { evt.returnValue = false; } } addEvent(enlarge, 'click', makeLarger, true);
very basic but useful JS tips, thank for sharing