jQuery in Action
88
CHAPTER 4
Events are where it happens!
to it if so. After this statement, the
event
parameter can be referenced regardless
of how it was made available to the handler.
The properties of the
Event
instance provide a great deal of information
regarding the event that has been fired and is currently being handled. This
includes details such as which element the event was triggered on, the coordi-
nates of mouse events, and which key was clicked for keyboard events.
includes details such as which element the event was triggered on, the coordi-
nates of mouse events, and which key was clicked for keyboard events.
But not so fast. Not only does Internet Explorer use a proprietary means to
get the
Event
instance to the handler, but it also uses a proprietary definition of
the
Event
class in place of the
W3C
-defined standard--we're not out of the object-
detection woods yet.
For example, to get a reference to the target element--the element on which the
event was triggered--we access the
target
property in standards-compliant brows-
ers and the
srcElement
property in Internet Explorer. We deal with this inconsis-
tency by employing object detection with a statement such as the following:
var target = (event.target) ? event.target : event.srcElement;
This statement tests if
event.target
is defined and, if so, assigns its value to the
local
target
variable; otherwise, it assigns
event.srcElement
. We take similar
steps for other
Event
properties of interest.
Up until this point, we've acted as if event handlers are only pertinent to the
elements that serve as the trigger to an event--the image element of listing 4.1,
for example. But events propagate throughout the
for example. But events propagate throughout the
DOM
tree. Let's find out
about that.
Event bubbling
When an event is triggered on an element in the
DOM
tree, the event-handling
mechanism of the browser checks to see if a handler has been established for that
particular event on that element and, if so, invokes it. But that's hardly the end of
the story.
particular event on that element and, if so, invokes it. But that's hardly the end of
the story.
After the target element has had its chance to handle the event, the event
model checks with the parent of that element to see if it has established a handler
for the event type, and if so, it's also invoked--after which its parent is checked,
then its parent, then its parent, and on and on, all the way up to the top of the
for the event type, and if so, it's also invoked--after which its parent is checked,
then its parent, then its parent, and on and on, all the way up to the top of the
DOM
tree. Because the event handling propagates upward like the bubbles in a
champagne flute (assuming we view the
DOM
tree with its root at the top), this
process is termed event bubbling.
Let's modify the example of listing 4.1 so that we can see this process in action.
Consider the code in listing 4.2.