Home > English, Tech Crunch > JavaScript: Event Registration

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

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: