A Javascript Event Handler Script

Do you remember the dark days of HTML? A million inline properties that were a nightmare to handle even on the smallest websites. Thankfully CSS came along, and good developers now control most of their styling through a centralized stylesheet.

So why shouldn’t we do the same thing with Javascript? A bunch of inline events all over the document with onclick="" or onmouseover="" is just as bad as inline styles or font-tags.

However, attaching these event listeners from a central Javascript poses a challenge, since the listener implementation differs from browser to browser. While there are a lot of scripts to attach event listeners, in 2001 Scott Andrew came up with an excellent cross-browser event handler script.

For our Javascript code-library, we’ll use a modification of it:

function addEvent(obj, evType, fn){ 
    if (obj.addEventListener){ 
        obj.addEventListener(evType, fn, false); 
        return true; 
    } else if (obj.attachEvent){ 
        var r = obj.attachEvent("on"+evType, fn); 
        return r; 
    } else { 
        return false; 
    }
}

This is very easy to call, just pass it the object you want to attach the listener to, a string for the event type (e.g. “click”, “load” or “blur”), and the name of the function to execute when that listener fires.

For instance if we wanted to run the function init() when the page loaded, we would just pass in the window object:


addEvent( window, "load", init );

Be Sociable, Share!

Tags: , , ,

Leave a Comment