jQuery in Action
Understanding the browser event models
87
Note how the value of the attribute is used as the body of the generated function,
and note that the function is created so that the
and note that the function is created so that the
event
parameter is available
within the generated function.
Before we move on to examining what that parameter is all about, we should
note that using the attribute mechanism of declaring
DOM
Level 0 event handlers
violates the precepts of Unobtrusive JavaScript that we explored in section 1.2.
When using jQuery in our pages, we should adhere to the principles of Unobtru-
sive JavaScript and avoid mixing behavior defined by JavaScript with display
markup. We'll see that jQuery provides a better way to declare event handlers
than either of these means before the end of this chapter.
When using jQuery in our pages, we should adhere to the principles of Unobtru-
sive JavaScript and avoid mixing behavior defined by JavaScript with display
markup. We'll see that jQuery provides a better way to declare event handlers
than either of these means before the end of this chapter.
But first, let's examine what that
event
parameter is all about.
The Event instance
When an event handler is fired, an instance of a class named
Event
is passed to
the handler as its first parameter in most browsers. Internet Explorer, always the
life of the party, does things in its own proprietary way by tacking the
life of the party, does things in its own proprietary way by tacking the
Event
instance onto a
window
property named
event
.
In order to deal with this discrepancy we'll often see the following used as the
first statement in an event handler:
if (!event) event = window.event;
This levels the playing field by using object detection to check if the
event
param-
eter is undefined (or null) and assigning the value of the window's
event
property
Figure 4.1 Waving the mouse over the image and clicking it result in the event
handlers firing and emitting their messages to the console.
handlers firing and emitting their messages to the console.