HTML and CSS Reference
In-Depth Information
element.attachEvent("on" + type, function () {
// Pass event as argument to the listener and
// correct it's this value. IE calls the listener
// with the global object as this.
return listener.call(element, window.event);
});
} else {
element.addEventListener(type, listener, false);
}
}
This piece of code makes many mistakes, but alas, is representative of lots of code
in use even to this day. The user agent sniff is potentially dangerous in a couple of
ways; it assumes that any browser that does not appear to be Internet Explorer sup-
ports addEventListener ; it assumes that any browser appearing to be Internet
Explorer supports attachEvent , and makes no room for a future Internet Ex-
plorer that supports the standardized API. In other words, the code will err on some
browsers and definitely will need updating whenever Microsoft releases a standards-
compliant browser. We will improve on the example throughout this chapter.
10.1.2 Object Detection
As sniffing the user agent string became increasingly hard due to dishonest browsers,
browser detection scripts grew more sophisticated. Rather than inspecting the user
agent string, developers discovered that the type of browser could very often be
determined by checking for the presence of certain objects. For instance, the script
in Listing 10.2 updates our previous example to avoid the user agent string and
rather infer type of browser based on some objects known to exist only in Internet
Explorer.
Listing 10.2 Using object detection to sniff browser
function addEventHandler(element, type, listener) {
// Bad example, don't try this at home
if (window.ActiveXObject) {
element.attachEvent("on" + type, function () {
return listener.call(element, window.event);
});
} else {
element.addEventListener(type, listener, false);
}
}
 
Search WWH ::




Custom Search