Chapter 18 we’ll see a readystatechange event that is triggered on an XMLHttpRequest
object, for example.
An event handler or event listener is a function that handles or responds to an event.
Applications register their event handler functions with the web browser, specifying an
event type and an event target. When an event of the specified type occurs on the
specified target, the browser invokes the handler. When event handlers are invoked for
an object, we sometimes say that the browser has “fired”, “triggered”, or “dispatched”
the event. There are a number of ways to register event handlers, and the details of
handler registration and invocation are explained in §17.2 and §17.3.
An event object is an object that is associated with a particular event and contains details
about that event. Event objects are passed as an argument to the event handler function
(except in IE8 and before where they are sometimes only available through the global
). All event objects have a
property that specifies the event type and
property that specifies the event target. (In IE8 and before, use
.) Each event type defines a set of properties for its associated event
object. The object associated with a mouse event includes the coordinates of the mouse
pointer, for example, and the object associated with a keyboard event contains details
about the key that was pressed and the modifier keys that were held down. Many event
types define only a few standard properties—such as
—and do not
carry much other useful information. For those events it is the simple occurrence of the
event, not the event details, that matter. This chapter does not have a specific section
covering the Event object. Instead, it explains event object properties when describing
specific event types. You can read more about the event object under the name
in the reference section.
Event propagation is the process by which the browser decides which objects to trigger
event handlers on. For events that are specific to a single object (such as the load event
on the Window object), no propagation is required. When certain kinds of events occur
on document elements, however, they propagate or “bubble” up the document tree. If
the user moves the mouse over a hyperlink, the mousemove event is first fired on the
element that defines that link. Then it is fired on the containing elements: perhaps
element, and the Document object itself. It is sometimes more
convenient to register a single event handler on a Document or other container element
than to register handlers on each individual element you’re interested in. An event
handler can stop the propagation of an event, so that it will not continue to bubble and
will not trigger handlers on containing elements. Handlers do this by invoking a method
1.Some sources, including the HTML5 specification, make a technical distinction between handlers and
listeners, based on the way in which they are registered. In this book we treat the two terms as synonyms.
2.Standards define a hierarchy of event object interfaces for different types of events. The Event interface
describes “plain” events with no extra details. The MouseEvent subinterface describes the additional
fields available in the event objects passed with mouse events, and the KeyEvent subinterface describes
the fields you can use with keyboard events, for example. In this book, the reference section collapses all
those common event interfaces into a single Event reference page.
446 | Chapter 17: Handling Events
How to C#: Basic SDK Concept of XDoc.PDF for .NET
You may add PDF document protection functionality into your C# program. to edit hyperlink of PDF document, including editing PDF url links and quick add hyperlink to pdf online; add hyperlinks to pdf
or setting a property of the event object. Event propagation is covered in detail in
In another form of event propagation, known as event capturing, handlers specially
registered on container elements have the opportunity to intercept (or “capture”) events
before they are delivered to their actual target. Event capturing is not supported by IE8
and earlier, and is not, therefore, commonly used. The ability to capture or “grab”
mouse events is required when processing mouse drag events, however, and we’ll see
how to do this in Example 17-2.
Some events have default actions associated with them. When a click event occurs on
a hyperlink, for example, the default action is for the browser to follow the link and
load a new page. Event handlers can prevent this default action by returning an ap-
propriate value, invoking a method of the event object, or by setting a property of the
event object. This is sometimes called “canceling” the event and is covered in §17.3.7.
With those terms defined, we can now move on to study events and event handling in
detail. The first section that follows is an overview of the many event types supported
by web browsers. It doesn’t cover any single kind of event in detail, but it lets you know
what kinds of events are available for use in your web applications. This section includes
cross-references to other parts of this book that demonstrate some of the events in
After the introductory section on event types, the next two sections explain how to
register event handlers and how the browser invokes those event handlers. Because of
ards support prior to IE9, both of these topics are more complicated than you might
The chapter ends with a series of examples that demonstrate how to work with a specific
types of events. These event-type-specific sections cover:
• Document loading and readiness events
• Mouse events
• Mouse wheel events
• Drag-and-drop events
• Key events
• Text input events
17.1 Types of Events
In the early days of the Web, client-side programmers made do with only a small set
of events: “load”, “click”, “mouseover”, and the like. These legacy event types are well
supported by all browsers and are the subject of §17.1.1. As the web platform has grown
to include more powerful APIs, the set of events has grown large. No single standard
17.1 Types of Events | 447
VB.NET PDF: Basic SDK Concept of XDoc.PDF
You may add PDF document protection functionality into your VB.NET program. to edit hyperlink of PDF document, including editing PDF url links and quick clickable pdf links; convert excel to pdf with hyperlinks
defines a complete set of events, and at the time of this writing, the number of events
supported by browsers is growing rapidly. These new events come from three sources:
• The DOM Level 3 Events specification, which after a long period of inactivity is
being actively worked on under the auspices of the W3C. DOM events are covered
• Many new APIs in the HTML5 specification (and related spin-off specifications)
define new events for things like history management, drag-and-drop, cross-
document messaging, and audio and video playback. §17.1.3 gives an overview of
iPhone, have required the definition of new touch and gesture event types. See
§17.1.4 for some Apple-specific examples.
Note that many of these new event types are not yet widely implemented and are defined
by standards that are still in draft stage. The subsections that follow provide an overview
of the events, but do not document each one in detail. The rest of this chapter covers
the event handling model comprehensively and includes lots of examples of working
with events that are well supported. If you understand how to work with events gen-
erally, you will be able to easily handle new event types as new web APIs are defined
Events can be grouped into some general categories, and knowing what these categories
are will help you to understand and organize the long list of events that follows:
Device-dependent input events
These are events that are directly tied to a specific input device, such as the mouse
or keyboard. They include legacy event types such as “mousedown”, “mouse-
move”, “mouseup”, “keydown”, “keypress”, and “keyup” and also new touch-
specific events like “touchmove” and “gesturechange”.
Device-independent input events
These are input events that are not directly tied to a specific input device. The click
event, for example, indicates that a link or button (or other document element)
has been activated. This is often done via a mouse click, but it could also be done
by keyboard or (on touch-sensitive devices) by gesture. The textinput event (which
is not yet widely implemented) is a device-independent alternative to the keypress
event and supports keyboard input as well as alternatives such as cut-and-paste
and handwriting recognition.
User interface events
UI events are higher-level events, often on HTML form elements that define a user
interface for a web application. They include the focus event (when a text input
field gains keyboard focus), the change event when the user changes the value
displayed by a form element, and the submit event when the user clicks a Submit
button in a form.
448 | Chapter 17: Handling Events
Some events are not triggered directly by user activity, but by network or browser
activity, and indicate some kind of lifecycle or state-related change. The load event,
fired on the Window object when the document is fully loaded, is probably the
most commonly used of these events. The DOMContentLoaded event (discussed
in §13.3.4) is another such event. The HTML5 history management mechanism
(§22.2) fires the popstate event in response to the browser’s Back button. The
HTML5 offline web application API (§20.4) includes online and offline events.
Chapter 18 shows how to use a readystatechange event to be notified when data
requested from a server is ready. Similarly, the new API for reading user-selected
local files (§22.6.5) uses events like “loadstart”, “progress”, and “loadend” for
asynchronous notification of I/O progress.
A number of web APIs defined by HTML5 and related specifications include their
own event types. The drag-and-drop API (§17.7) defines events such as “drag-
start”, “dragenter”, “dragover”, and “drop”. Applications that want to define cus-
tom drag sources or drop targets must handle some of these events. The HTML5
elements (§21.2) define a long list of associated event types
such as “waiting”, “playing”, “seeking”, “volumechange”, and so on. These events
are usually only of interest to web apps that want to define custom controls for
video or audio playback.
Timers and error handlers
Timers and error handlers (both of which are described in Chapter 14) are part of
events. Although timers and error handlers are not discussed in this chapter, it is
useful to think of them as related to event handling, and you may find it interesting
to reread §14.1 and §14.6 in the context of this chapter.
17.1.1 Legacy Event Types
The events you’ll use most often in your web apps are generally the ones that have been
around the longest and are universally supported: events for dealing with the mouse,
the keyboard, HTML forms, and the Window object. The sections below explain many
important details about these kinds of events.
22.214.171.124 Form events
Forms and hyperlinks were the first scriptable elements in a web page, way back in the
most stable and well-supported of all event types.
elements fire submit events
when the form is submitted and reset events when the form is reset. Button-like form
elements (including radio buttons and checkboxes) fire click events when the user in-
teracts with them. Form elements that maintain some kind of state generally fire change
events when the user changes their state by entering text, selecting an item, or checking
a box. For text input fields, a change event is not fired until the user has finished in-
17.1 Types of Events | 449
teracting with a form element and has tabbed or clicked to move focus to another
element. Form elements respond to keyboard focus changes by firing focus and blur
events when they gain and lose the focus.
These form-related events are all covered in more detail in §15.9.3. A few more notes
are in order here, however.
The submit and reset events have default actions that can be canceled by event handlers,
and some click events do, too. The focus and blur events do not bubble, but all the
other form events do. IE defines focusin and focusout events that do bubble as a useful
alternative to focus and blur. The jQuery library (see Chapter 19) emulates focusin and
focusout events for browsers that do not support them, and the DOM Level 3 Events
specification is standardizing them as well.
Finally, note that browsers other than IE trigger an input event on
text-input form elements whenever the user enters text (via the keyboard or cut-and-
paste) into the element. Unlike the change event, these input events are triggered for
each insertion. Unfortunately, the event object of an input event does not specify what
text has been input. (The new textinput event described later will be a useful alternative
to this event.)
126.96.36.199 Window events
Window events represent occurrences related to the browser window itself, rather than
any specific document content displayed inside the window. (For some of these events,
however, an event with the same name can be fired on document elements.)
The load event is the most important of these events: it is fired when a document and
all of its external resources (such as images) are fully loaded and displayed to the user.
The load event was discussed throughout Chapter 13. DOMContentLoaded and
readystatechange are alternatives to the load event: they are triggered sooner, when the
document and its elements are ready to manipulate, but before external resources are
fully loaded. §17.4 has examples of these document load-related events.
The unload event is the opposite of load: it is triggered when the user is navigating away
from a document. An unload event handler might be used to save the user’s state, but
it cannot be used to cancel navigation. The beforeunload event is similar to unload but
gives you the opportunity to ask the user to confirm that they really want to navigate
away from your web page. If a handler for beforeunload returns a string, that string will
be displayed to the user in a confirmation dialog before the new page is loaded, and
the user will have the opportunity to cancel her navigation and remain at your page.
property of the Window object is something like an event handler, and it
because it is invoked with different arguments. See §14.6 for details.
Individual document elements, such as
elements, can also register handlers for
load and error events. These are triggered when an external resource (the image, for
450 | Chapter 17: Handling Events
example) is fully loaded, or when an error occurs that prevents it from loading. Some
browsers also support (and HTML5 standardizes) an abort event, which is triggered
when an image (or other network resource) fails to load because the user stopped the
The focus and blur events described above for form elements are also used as Window
events: they are triggered on a window when that browser window receives or loses
keyboard focus from the operating system.
Finally, the resize and scroll events are fired on a Window when the user resizes or
scrolls the browser window. Scroll events can also be fired on any scrollable document
element, such as those with the CSS
property (§16.2.6) set. The event object
passed to resize and scroll event handlers is just an ordinary Event object and does not
have properties that specify how much resizing or scrolling occurred—you can deter-
mine the new window size and scrollbar position using the techniques shown in §15.8.
188.8.131.52 Mouse events
Mouse events are generated when the user moves or clicks the mouse over a document.
These events are triggered on the most deeply nested element that the mouse pointer
is over, but they bubble up through the document. The event object passed to mouse
event handlers has properties set that describe the position and button state of the
mouse and also specify whether any modifier keys were held down when the event
properties specify the position of the mouse in
window coordinates. The
properties specify which mouse button (if
any) was pressed. (See the
reference page, however, because these properties are
difficult to use portably.) The
properties are set
when the corresponding keyboard modifier keys are held down. And for click
property specifies whether this was a single, double, or triple click.
The mousemove event is triggered any time the user moves or drags the mouse. These
events occur frequently, so mousemove handlers must not trigger computationally in-
tensive tasks. The mousedown and mouseup events are triggered when the user presses
and releases a mouse button. By registering a mousedown handler that registers a
mousemove handler, you can detect and respond to mouse drags. Doing this properly
involves being able to capture mouse events so that you continue to receive mousemove
events even when the mouse has moved out of the element it started in. §17.5 includes
an example of handling drags.
After a mousedown and mouseup event sequence, the browser also triggers a click
event. The click event was described above as a device-independent form event, but it
is actually triggered on any document element, not just form elements, and it is passed
an event object with all of the extra mouse-related fields described above. If the user
clicks a mouse button twice in a row (within a sufficiently short amount of time), the
second click event will be followed by a dblclick event. Browsers often display a context
menu when the right mouse button is clicked. They generally fire a contextmenu event
17.1 Types of Events | 451
before displaying the menu, and if you cancel the event, you can prevent the display of
the menu. This is also an easy way to be notified of right mouse button clicks.
When the user moves the mouse so that it goes over a new element, the browser fires
a mouseover event on that element. When the mouse moves so that it is no longer over
an element, the browser fires a mouseout event on that element. For these events, the
event object will have a
property that specifies the other element involved
in the transition. (See the
reference page for the IE equivalent of the
property.) mouseover and mouseout events bubble like all of the mouse
events described here. This is often inconvenient, because when a mouseout handler
is triggered, you have to check whether the mouse actually left the element you are
interested in or if it merely transitioned from one child of the element to another. Be-
cause of this, IE supports nonbubbling versions of these events known as mouseenter
and mouseleave. jQuery emulates support for these events in browsers other than IE
(see Chapter 19), and the DOM Level 3 Events specification standardizes them.
When the user rotates the mouse wheel, browsers trigger a mousewheel event (or, in
Firefox, a DOMMouseScroll event). The event object passed with these events includes
properties that specify how much, and in which direction, the wheel was rotated.
The DOM Level 3 Events specification is standardizing a more general multidimen-
sional wheel event that, if implemented, will supersede both mousewheel and
DOMMouseScroll. §17.6 includes a mousewheel event example.
184.108.40.206 Key events
When the web browser has keyboard focus, it generates events each time the user
presses or releases a key on the keyboard. Keyboard shortcuts that have meaning to the
operating system or to the browser itself are often “eaten” by the OS or browser and
on whatever document element has keyboard focus, and they bubble up to the docu-
ment and window. If no element has the focus, the events are triggered directly on the
document. Keyboard event handlers are passed an event object with a
specifies what key was pressed or released. In addition to
, the event object for
key events also has
that describe the state of the
keyboard modifier keys.
The keydown and keyup events are low-level keyboard events: they are triggered when-
ever a key (even a modifier key) is pressed or released. When a keydown event generates
a printable character, an additional keypress event is triggered after the keydown but
before the keyup. (In the case of a key that is held down until it repeats, there may be
many keypress events before the keyup event.) The keypress event is a higher-level text
event, and its event object specifies the character that was generated, not the key that
The keydown, keyup, and keypress events are supported by all browsers, but there are
some interoperability problems because the values of the
property of the event
object have never been standardized. The DOM Level 3 Events specification, described
452 | Chapter 17: Handling Events
Documents you may be interested
Documents you may be interested