jQuery in Action
98
CHAPTER 4
Events are where it happens!
Explorer Model, we even have to diverge our code when establishing the han-
dlers in the first place.
dlers in the first place.
Well, jQuery is going to make our lives simpler by hiding these browser dispar-
ities from us as much as it possibly can. Let's see how!
4.2 The jQuery Event Model
Although it's true that the creation of Rich Internet Applications requires a hefty
reliance on event handling, the thought of writing event-handling code on a large
scale while dealing with the browser differences is enough to daunt even the most
intrepid of page authors.
reliance on event handling, the thought of writing event-handling code on a large
scale while dealing with the browser differences is enough to daunt even the most
intrepid of page authors.
We could hide the differences behind an
API
that abstracts the differences
away from our page code, but why bother when jQuery has already done it for us?
jQuery's event implementation, which we'll refer to informally as the jQuery
Event Model, exhibits the following features:
Provides a unified method for establishing event handlers
Allows multiple handlers for each event type on each element
Uses standard event-type names: for example, click or mouseover
Makes the
Event
instance available as a parameter to the handlers
Normalizes the
Event
instance for the most often used properties
Provides unified methods for event canceling and default action blocking
With the notable exception of support for a capture phase, the feature set of the
jQuery Event Model closely resembles that of the Level 2 Model while supporting
both standards-compliant browsers and Internet Explorer with a single
jQuery Event Model closely resembles that of the Level 2 Model while supporting
both standards-compliant browsers and Internet Explorer with a single
API
. The
omission of capture phase should not be an issue for the vast majority of page
authors who never use it (or even know it exists) due to its lack of support in
authors who never use it (or even know it exists) due to its lack of support in
IE
.
Is it really that simple? Let's find out.
4.2.1 Binding event handlers using jQuery
Using the jQuery Event Model, we can establish event handlers on
DOM
elements
with the
bind()
command. Consider the following simple example:
$('img').bind('click',function(event){alert('Hi there!');});
This statement binds the supplied inline function as the click event handler for
every image on a page. The full syntax of the
every image on a page. The full syntax of the
bind()
command is as follows: