↑
Main Page
Cross-Browser Events
Cross-Browser Events
Up until this point, you have seen many different types of browser and feature detection used in each
example. In actual code, you want to try to minimize the number of times you use such detection in the
main section of code. To achieve this, most developers come up with a cross-browser approach to events
so that all the browser and feature detection is done behind the scenes. This section guides you through
the creation of such an approach.
The purpose of the cross-browser code in this section is to equalize, as much as possible, the differences
between the IE event model and the DOM event model, allowing one set of code to run across all major
browsers almost identically. Of course, some limitations exist, such as IE’s lack of support for bi-directional
event flow, but it is still possible to cover 80 to 90% of all cases.
The EventUtil object
Whenever you are planning on creating multiple functions that are used in the same task, it’s always
best to create a container object to manage them. Doing so makes it easy to figure out where the function
is defined when debugging.
In this case, the
EventUtil
object is the container for all the event-related functions defined in this sec-
tion. Because there are no properties and you only need one instance of this object, there’s no need to
define a class:
var EventUtil = new Object;
Adding/removing event handlers
As you saw earlier, IE uses the
attachEvent()
method to assign any number of event handlers to an
element, whereas the DOM uses
addEventListener()
. The first method of the
EventUtil
object cre-
ates a common way to assign event handlers and is called
addEventHandler()
(so as not to be con-
fused with either browser ’s implementation). This method accepts three arguments: the object to assign
the event handler to, the name of the event to handle, and the function to assign. Because IE doesn’t sup-
port event capturing, this method assigns event handlers during bubbling only. Inside the body of the
method is a simple detection algorithm designed to use the correct functionality at the correct time:
EventUtil.addEventHandler = function (oTarget, sEventType, fnHandler) {
if (oTarget.addEventListener) { //for DOM-compliant browsers
oTarget.addEventListener(sEventType, fnHandler, false);
} else if (oTarget.attachEvent) { //for IE
oTarget.attachEvent(“on” + sEventType, fnHandler);
} else { //for all others
oTarget[“on” + sEventType] = fnHandler;
}
};
The code in this method uses feature detection to determine which way to add an event handler. The
first branch of the
if
statement is for DOM-compliant browsers that support the
addEventListener()
method. When the browser is DOM-compliant, the event handler is added using
addEventListener()
with the last parameter equal to
false
, specifying the bubbling phase.
292
Chapter 9
12_579088 ch09.qxd 3/28/05 11:39 AM Page 292
Free JavaScript Editor
Ajax Editor
©
→