HTML and CSS Reference
In-Depth Information
10.2.1 Testing for Existence
Consider once again our event handling example. Listing 10.3 uses object detection
as before, but rather than testing objects known to only exist in certain browsers, it
tests the objects we're actually interested in using.
Listing 10.3 Using feature detection to branch event handling
function addEventHandler(element, type, listener) {
if (element.addEventListener) {
element.addEventListener(type, listener, false);
} else if (element.attachEvent && listener.call) {
element.attachEvent("on" + type, function () {
return listener.call(element, window.event);
});
} else {
// Possibly fall back to event properties or abort
}
}
This example has a much better chance of surviving in the wild, and is very un-
likely to need updating whenever a new browser is released. Internet Explorer 9 is
scheduled to implement addEventListener , and even if this browser keeps
attachEvent side by side with it to ensure backwards compatibility, our
addEventHandler is going to do the right thing. Prodding for features rather
than browser type means our script will use addEventListener if it's available
without any manual interference. The preceding browser detection-based scripts
will all have to be updated in such a scenario.
10.2.2 Type Checking
Although Listing 10.3 prods the correct objects before using them, the feature test
is not completely accurate. The fact that the addEventListener property exists
is not necessarily a guarantee that it will work as expected. The test could be made
more accurate by checking that it is callable, as Listing 10.4 shows.
Listing 10.4 Type-checking features
function addEventHandler(element, type, listener) {
if (typeof element.addEventListener == "function") {
element.addEventListener(type, listener, false);
} else if (typeof element.attachEvent == "function" &&
typeof listener.call == "function") {
element.attachEvent("on" + type, function () {
 
Search WWH ::




Custom Search