JavaScript: Event Registration

This article was first written in May 2005 for the BeezNest technical
website (


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.


/* Author: Scott Andrew LePera (
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){
                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){
                return true;
        } else if (obj.detachEvent){
                var r=obj.detachEvent("on"+evType,fn);
                return r;
        } else {
                alert("Handler could not be removed.");


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


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 It’s a website that lets you type (or paste)...

Quick Contact Form