Java Reference
In-Depth Information
The first thing you do inside this function is to check if the given object has an addEventListener()
method:
if (obj.addEventListener) {
obj.addEventListener(type, fn)
}
If addEventListener() exists, you call it and pass the type and fn parameters to it. But if
addEventListener() doesn't exist, you want to call attachEvent() :
else {
obj.attachEvent("on" + type, fn);
}
}
Here, you append on to the value contained within the type variable. This way, you can pass the
standard name of the event, such as click , to the addListener() function, and it'll work with both
standards‐compliant browsers and old‐IE.
To use this function, you'd call it like this:
addListener(elementObj, "click", eventHandler);
Assuming elementObj is an element object and eventHandler() is a function, you'd successfully
register an event listener/handler for standards‐compliant browsers and old‐IE.
Following the pattern used in the addListener() function, you can write an event utility object that
makes it easier to write cross‐browser, event‐driven code. An event utility object should provide the
capability to add and remove listeners, as well as get the event target.
a Cross‐Browser Event Utility
trY it out
In this Try It Out, you will write a utility to make it easier to write cross‐browser code. Open your text
editor and type the following:
var evt = {
addListener: function(obj, type, fn) {
if (obj.addEventListener) {
obj.addEventListener(type, fn);
} else {
obj.attachEvent("on" + type, fn);
}
},
removeListener: function(obj, type, fn) {
if (obj.removeEventListener) {
obj.removeEventListener(type, fn);
} else {
obj.detachEvent("on" + type, fn);
}
},
getTarget: function(e) {
if (e.target) {
Search WWH ::




Custom Search