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);


It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on TumblrEmail this to someone

Leave a Reply

Your email address will not be published. Required fields are marked *