JavaScript: Event Registration

This article was first written in May 2005 for the BeezNest technical
website (http://glasnost.beeznest.org/articles/255).

Description

Attach an event to an element by defining the type of event to listen for, the handler function to execute when the event is fired, and whether you want to use event capture.

Code

/* Author: Scott Andrew LePera (www.scottandrew.com)
Default value for useCapture has been set to false because: "If it is true,
the event listener should not fire for any element the event listener is
registered on." */
function addEvent(obj,evType,fn,useCapture){
        if (isNaN(useCapture)) useCapture = false;
        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 (isNaN(useCapture)) useCapture=false;
        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.");
        }
}

Usage

function windowOnLoad(){
        // Some stuff
}
addEvent(window, 'load', windowOnLoad);

Links


Related Posts

FCKeditor bugs in Dokeos implementation – the debugging process

For the sake of remembering myself of what I did, not being an...

Test your JavaScript code with JSFiddle

I just discovered jsfiddle.net. It’s a website that lets you type (or paste)...

Quick Contact Form