Java Reference
In-Depth Information
By assigning null , you have overwritten the previous value contained by the property, and that
introduces the main problem with these types of event handlers: you can assign only one function to
handle a given event. For example:
img2.onclick = functionOne;
img2.onclick = functionTwo;
The first line of this code assigns a function called functionOne() to an element's onclick property. The
second line, however, overwrites the value of img2.onclick by assigning it a new value. So, when the user
clicks img2 , only functionTwo() executes. That behavior is fine if it's what you actually want, but more
often than not, you want both functionOne() and functionTwo() to execute when img2 is clicked.
You can do that thanks to the standard DOM event model.
the standard event model
Up until this point, you've been working with nonstandard techniques for listening for events. Yes,
they work in every browser, but that support exists primarily for backward compatibility. They are
not guaranteed to work in future browser versions.
First, some history. The two major browsers in the late 1990s were Internet Explorer 4 and
Netscape 4—the first browser war. Not surprisingly, both browser vendors implemented vastly
different DOMs and event models, fragmenting the web into two groups: websites that catered to
Netscape only, and websites that catered to IE only. Very few developers chose the frustrating task
of cross‐browser development.
Obviously, a need for a standard grew from this fragmentation and frustration. So the W3C
introduced the DOM standard, which grew into DOM level 2, which included a standard event model.
The DOM standard defines an object called EventTarget . Its purpose is to define a standard way
of adding and removing listeners for an event on the target. Every element node in the DOM is an
EventTarget , and as such, you can dynamically add and remove event listeners for a given element.
The standard also describes an Event object that provides information about the element that
has generated an event and enables you to retrieve it in script. It provides a set of guidelines for a
standard way of determining what generated an event, what type of event it was, and when and
where the event occurred. If you want to make it available in script, it must be passed as a parameter
to the function connected to the event handler.
Note Older versions of Internet Explorer (8 and below) do not implement the
DOM event model. The code in this section only works with modern browsers:
IE9+, Chrome, Firefox, Opera, and Safari.
Connecting Code to events—the standard Way
The EventTarget object defines two methods for adding and removing event listeners (remember
that an EventTarget is an element). The first method, addEventListener() , registers an event
 
Search WWH ::




Custom Search