Sunday, July 27, 2008

Cross-browser Javascript Events

So you're trying to convert your website from an IE specific site into a cross-browser compatible web site. You've probably noticed that the event object is not available in the current event as is the norm for Internet Explorer. In fact when supporting events in a cross-browser manner you must plan ahead.

There are three ways that you typcially hook up events in a browser. For example to hook up the onclick event you could add the onclick attribute to the tag you want to bind to:

<div id="test" onclick="doit();">Some Content</div>

Another way is to select the tag in javascript and use the onclick attribute as follows:

document.getElementById("test").onclick = doit;

and finally, the last method is to use the bind method which is called attachEvent in Internet Explorer and a similar event is called addEventListener in W3C browsers:

document.getElementById("test").attachEvent("onclick", doit);

The project I'm working on typically uses the first and last of these methods. In Internet Explorer, you can expect that the window.event object contains the current event. In W3C compatible browsers, for the first method above, you have access to a special event keyword that you can pass to your function. In the last two methods, the event is implicitly passed in.

Here's an example of using the event keyword for the first method:

<div id="test" onclick="doit(event, "myarg");">Some Content</div>

For the second method, here's an example of how to pass multiple parameters assuming that the event object is passed implicitly to the specified function:

document.getElementById("test").onclick = function(evt){doit(evt, "myarg");};


Finally, in the last example, here is how you'd pass the event object to W3C browsers:

document.getElementById("test").addEventListener("click", function(evt){doit(evt, "myarg");}, false);

That's it so far. In my next blog I show you how to take this information and create some rudimentary functions that will allow you to easily support events in a cross-browser manner.

1 comment:

Anonymous said...

Great information. --brent