Monday, August 18, 2008

Generic Events - Part 1

In my previous article, I discussed the different ways to bind to events in a browser agnostic fashion. In this article, I discuss how to create a generic function allowing you to bind to events in almost any browser.

In general you use either the Internet Explorer specific attachEvent or the W3C addEventListener functions when programmatically binding to events.

These functions are similar in behavior and we can make use of that to create a generic function that use either of these. One of the most frustrating things I've found with the W3C event support is the fact that it doesn't support the window.event object. Instead, it implicitly passes the event object to the function. I had to get that out and I will discuss it in future blogs, however, it has nothing to do with this article:-)

Here is the proper use of attachEvent in an IE browser:

document.getElementById("test").attachEvent("onclick", function(){alert('onclick was called');});

And here is the proper use of addEventListener in W3C browsers:

document.getElementById("test").addEventListener("click", function(evt){alert('click was called'), false);

Note that you either use the name of a function or an anonymous function. As well addEventListener has an extra parameter for capturing events. At this point we will ignore that extra parameter by passing in false.

Okay, so now that we know how to use them in the simplest case, here is a function that allows us to add events in a generic manner:

function addEvent(elem, eventName, func)
{
if (elem.attachEvent)
{
elem.attachEvent('on' + eventName, func);
} else if(elem.addEventListener)
{
elem.addEventListener(eventName, func, false);
}
}


Note that addEventListener doesn't prefix events with the on keyword so when calling the addEvent function just pass in the event name and we append the on prefix as necessary.

That's it for now. This function went a long way when converting my client's web site to support W3C browsers. In fact you won't believe how easy it is to use and begin replacing once you get started.

No comments: