Java Reference
In-Depth Information
return e.target;
}
return e.srcElement;
},
preventDefault: function(e) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
};
Save it as
eve nt‐utility.js
.
Using object literal notation, you create an object called
evt
. Its purpose is to make it easier to write
cross‐browser code:
var evt = {
The first method you write is the
addListener()
method, and it is exactly the same as the
addListener()
function you previously wrote:
addListener: function(obj, type, fn) {
if (obj.addEventListener) {
obj.addEventListener(type, fn);
} else {
obj.attachEvent("on" + type, fn);
}
},
If the browser supports
addEventListener()
, it uses the method to register an event listener.
Otherwise, the browser calls
attachEvent()
.
The next method is
removeListener()
. As its name implies, it removes a listener that was added
previously to an object:
removeListener: function(obj, type, fn) {
if (obj.removeEventListener) {
obj.removeEventListener(type, fn);
} else {
obj.detachEvent("on" + type, fn);
}
},
The code is almost identical to
addListener()
except for a few key changes. First, it checks if the given
object has a
removeEventListener()
method, and if so, it calls
removeEventListener()
. If not, it
assumes the browser is old‐IE and calls
detachEvent()
.
The third method,
getTarget()
, is responsible for getting the event target from the event object:
getTarget: function(e) {
if (e.target) {
return e.target;