Cross-browser event handling

Microsoft Internet Explorer (IE) does not support DOM Level 2 event handling, but have implemented their own event functions (attachEvent and detachEvent). I have made a function which will work in all modern browser. It will use W3C’s addEventListener if it is supported otherwise it will use IE’s event functions.

How to use:

execute doOnLoad() function at onloadaddEvent(window,’onload’, doOnLoad );

execute doHello() function when clicking on the helloWorld elementaddEvent(‘helloWorld’,'onclick’, doHello);

This is the script:

function addEvent(el,type,listener,useCapture) {
if(typeof el == 'string') {
el = document.getElementById(el);}
if(!el){return false;}
if(document.addEventListener) {
// W3C DOM Level 2 Events - used by Mozilla, Opera and Safari
if(!useCapture) {useCapture = false;} else {useCapture = true;}
el.addEventListener(type,listener,useCapture); }
else {
// MS implementation - used by Internet Explorer
el.attachEvent(type, listener); }}

function removeEvent(el,type,listener,useCapture) {
if(typeof el == 'string') {
el = document.getElementById(el);}
if(!el){return false;}
if(document.removeEventListener) {
// W3C DOM Level 2 Events - used by Mozilla, Opera and Safari
if(!useCapture) {useCapture = false;}
else {useCapture = true;}
el.removeEventListener(type,listener,useCapture); }
else {
// MS implementation - used by Internet Explorer
el.detachEvent(type, listener); }}

About this entry