jQuery in Action
106
CHAPTER 4
Events are where it happens!
4.2.4 Affecting the event propagation
In addition to standardizing the most-used properties of the
Event
instance,
jQuery provides the same benefit for the standard methods used to affect event
propagation.
propagation.
The
stopPropagation()
method will prevent the event from bubbling further
up the
DOM
tree (if needed, refer back to figure 4.4 for a reminder of how events
propagate), and the
preventDefault()
method will cancel any semantic action
that the event might cause. Some examples of such semantic actions are link tra-
versal for
versal for
<a>
elements, forms submissions, and toggling the state of check boxes
on a click event.
If we want to both stop the propagation of the event, as well as cancel its
default behavior, we can return
false
as the return value of the listener function.
In addition to allowing us to set up event handling in a browser-independent
manner, jQuery provides a set of commands that gives us the ability to trigger
event handlers under script control. Let's look at those.
event handlers under script control. Let's look at those.
4.2.5 Triggering event handlers
Event handlers are designed to be invoked when their associated event triggers
the propagation of the event through the
the propagation of the event through the
DOM
hierarchy. But there may be times
when we want to trigger the execution of a handler under script control. We could
define such event handlers as top-level functions so that we can invoke them by
name, but as we've seen, defining event handlers as inline anonymous functions
is much more common and so darned convenient!
define such event handlers as top-level functions so that we can invoke them by
name, but as we've seen, defining event handlers as inline anonymous functions
is much more common and so darned convenient!
jQuery has provided means to assist us in avoiding top-level functions by
defining a series of methods that will automatically trigger event handlers on our
behalf under script control. The most general of these commands is
behalf under script control. The most general of these commands is
trigger()
,
whose syntax is as follows:
Command syntax: trigger
trigger(eventType)
Invokes any event handlers established for the passed event type for all matched elements
Parameters
eventType
(String) Specifies the name of the event type for handlers which are
to be invoked
Returns
The wrapped set
The wrapped set