Java Reference
In-Depth Information
} else {
// use attachEvent()
}
When writing cross‐browser JavaScript, you always want to check for standards compliance
first because some browsers may support both options. For example, IE9 and IE10 support
both
addEventListener()
and
attachEvent()
. If you check for
attachEvent()
instead of
addEventListener()
, like this:
// wrong! Do not do!
if (typeof attachEvent != "undefined") {
// use attachEvent
} else {
// use addEventListener
}
IE9 and IE10 will use
attachEvent()
instead of
addEventListener()
. We know that
attachEvent()
exhibits different behavior than
addEventListener()
, and as such, we want to avoid that behavior as
much as possible. Plus, we always want to use standards‐compliant code because it is guaranteed to
work in every standards‐compliant browser.
The previous example uses the
typeof
operator to determine if the
addEventListener()
method is
not undefined, but you can simplify the code by using
addEventListener
as a truthy or falsy value,
like this:
if (addEventListener) {
// use addEventListener()
} else {
// use attachEvent()
}
Whether you use the
typeof
operator or truthy/falsy values, either approach will give you the same
results. Just keep in mind that you want to be consistent as you write your code. If you use
typeof
,
use it for all of your feature‐detection code.
So with this in mind, you can write a function like this:
function addListener(obj, type, fn) {
if (obj.addEventListener) {
obj.addEventListener(type, fn)
} else {
obj.attachEvent("on" + type, fn);
}
}
Let's break down this code. Here, you define a function called
addListener()
. It has three
parameters—the object to register the event listener on, the event type, and the function to execute
when the event fires:
function addListener(obj, type, fn) {