W3C

Document Object Model (DOM) Level 3 Events Specification

W3C Working Draft 07 September 2010

This version:
http://www.w3.org/TR/2010/WD-DOM-Level-3-Events-20100907
Latest stable version:
http://www.w3.org/TR/DOM-Level-3-Events
Previous version:
http://www.w3.org/TR/2009/WD-DOM-Level-3-Events-20090908
Editor's Draft:
http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html
Editors:
Doug Schepers, W3C
Björn Höhrmann, Invited Expert (until December 2007)
Philippe Le Hégaret, W3C (until November 2003)
Tom Pixley, Netscape Communications Corporation (until July 2002)

Abstract

This specification defines the Document Object Model Events Level 3, a generic platform- and language-neutral event system which allows registration of event handlers, describes event flow through a tree structure, and provides basic contextual information for each event. The Document Object Model Events Level 3 builds on the Document Object Model Events Level 2 [DOM2 Events].

Status of This Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This document is the Last Call Working Draft of the Document Object Model Level 3 Events (DOM3 Events) specification. This document was previously published as a W3C Note, pending further feedback from implementers, and is now being revised to reflect the current state of implementation. It is expected that this specification will progress to W3C Recommendation status after review and refinement.

The Web Applications Working Group (WebApps WG) believes this specification to be feature complete, subject to further feedback during the Last Call period. The Last Call period extends through 18 October 2010. The public is encouraged to send comments to the WebApps Working Group's public mailing list for DOM specifications www-dom@w3.org (archive). See W3C mailing list and archive usage guidelines.

This document is produced by the Web Applications WG, part of the Rich Web Clients Activity in the W3C Interaction Domain. It is expected that this document will progress along the W3C's Recommendation track. Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

You can find the latest Editor's Draft of this document in the W3C's CVS repository, which is updated on a regular basis.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

Implementers should be aware that this document is not stable. Implementers who are not taking part in the discussions are likely to find the specification changing out from under them in incompatible ways. Vendors interested in implementing this document before it eventually reaches the Candidate Recommendation stage should join the aforementioned mailing lists and take part in the discussions.

Table of Contents

1. Document Object Model Events

1.1 Introduction

DOM Events is designed with two main goals. The first goal is the design of an event system which allows registration of event listeners and describes event flow through a tree structure. Additionally, the specification will provide standard modules of events for user interface control and document mutation notifications, including defined contextual information for each of these event modules.

The second goal of DOM Events is to provide a common subset of the current event systems used in existing browsers. This is intended to foster interoperability of existing scripts and content. It is not expected that this goal will be met with full backwards compatibility. However, the specification attempts to achieve this when possible.

1.2 Conformance

This section is normative.

Within this specification, the key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” are to be interpreted as described in RFC 2119 [RFC2119]. However, for readability, these words do not necessarily appear in uppercase in this specification.

This specification is to be understood in the context of the DOM Level 3 Core specification [DOM3 Core] and the general considerations for DOM implementations apply. For example, behavior in exceptional circumstances (such as when a null argument is passed when null was not expected) is discussed under DOMException, and handling of namespace URIs is discussed in XML Namespaces. For additional information about conformance, please see the DOM Level 3 Core specification [DOM3 Core]. A user agent is not required to conform to the entirety of another specification in order to conform to this specification, but it must conform to the specific parts of any other specification which are called out in this specification (e.g. a conforming DOM3 Events user agent must support the DOMString data type as defined in DOM3 Core, but need not support every method or data type defined in DOM3 Core in order to conform to DOM3 Events).

This specification defines several classes of conformance for different user agents, specifications, and content authors:

Web browsers and other dynamic or interactive user agents

A dynamic or interactive user agent, referred to here as a “browser” (be it a Web browser, AT (Accessibility Technology) application, or other similar program), conforms to DOM Level 3 Events if it supports the Core module defined in [DOM3 Core], the Event dispatch and DOM event flow mechanism, all the interfaces and events with their associated methods, attributes, and semantics defined in this specification which are not marked as deprecated, and the complete set of character values and key values in the Key Values Set (subject to platform availability), as well as all other normative requirements defined in this specification. A conforming browser must dispatch events appropriate to the given EventTarget when the conditions defined for that event type have been met.

A browser conforms specifically to the DOM Level 3 Events Architecture if it implements the DOM Event Architecture and Basic Event Interfaces, regardless of its support for any other event interfaces or event types defined in this specification. A browser conforms specifically to the DOM Level 3 Events Module if it implements the interfaces and its related event types specified in the Events Module, and to each event interface if it implements that interface and its related event types.

A conforming browser must support scripting, declarative interactivity, or some other means of detecting and dispatching events in the manner described by this specification, and with the attributes specified for that event type. A declarative browser may still conform to this specification if it does not directly support or expose the methods defined for the DOM Level 3 Events interfaces, but it should provide compatible functionality by other means.

In addition to meeting all other conformance criteria, a conforming browser may implement features of this specification marked as deprecated, for backwards compatibility with existing content, but such implementation is discouraged.

A conforming browser may also support features not found in this specification, but which use the Event dispatch and DOM event flow mechanism, interfaces, events, or other features defined in DOM Level 3 Events, and may implement additional interfaces and event types appropriate to that implementation. Such features may be later standardized in future specifications.

A browser which does not conform to all required portions of this specification must not claim conformance to DOM Level 3 Events. Such an implementation which does conform to portions of this specification may claim conformance to those specific portions.

Authoring tools

A content authoring tool conforms to DOM Level 3 Events if it produces content which uses the event types and Event dispatch and DOM event flow model, consistent in a manner as defined in this specification. A content authoring tool must not claim conformance to DOM Level 3 Events for content it produces which uses features of this specification marked as deprecated in this specification. A conforming content authoring tool should provide to the content author a means to use all event types and interfaces appropriate to all host languages in the content document being produced.

Content authors and content

A content author creates conforming DOM Level 3 Events content if that content uses the event types and Event dispatch and DOM event flow model, consistent in a manner as defined in this specification. A content author should not use features of this specification marked as deprecated, but should rely instead upon replacement mechanisms defined in this specification and elsewhere. Conforming content must use the semantics of the interfaces and event types as described in this specification, and must follow best practices as described in accessibility and internationalization guideline specifications. Issue: define specific guideline specifications.

Specifications and host languages

A specification or host language conforms to DOM Level 3 Events if it references and uses the Event dispatch and DOM event flow mechanism, interfaces, events, or other features defined in this specification, and does not extend these features in incompatible ways. A specification or host language conforms specifically to the DOM Level 3 Events Architecture if it references and uses the DOM Event Architecture and Basic Event Interfaces, regardless of its use of any other event interfaces or event types defined in this specification. A specification or host language conforms specifically to the DOM Level 3 Events Module if it references and uses the interfaces and its related event types specified in the Events Module, and to each event interface if it references and uses that interface and its related event types. A conforming specification may define additional interfaces and event types appropriate to that specification, or may extend the DOM Level 3 Events interfaces and event types in a manner that does not contradict or conflict with the definitions of those interfaces and event types in this specification. Events defined in conforming specifications must not have name conflicts with known languages, and should be defined in a manner that can be generalized for use with other specifications conforming to DOM Level 3 Events, as much as is possible. Specifications or host languages which reference DOM Level 3 Events should not use or recommend features of this specification marked as deprecated, but should point instead to the indicated replacement for that the feature. Editors of specifications referring to DOM Level 3 Events should consult with the Working Group responsible for this specification when using or extending the features defined in this specification.

1.3 Feature Detection

This section is normative

A conforming DOM Level 3 Events user agent must implement the DOMImplementation.hasFeature() method to allow content authors to detect for support of features defined in this specification. Refer to DOM Features in [DOM3 Core] for additional information on feature strings.

Note: The DOMImplementation.hasFeature() method has been of limited utility to content authors in some instances, because of imprecision in conformance criteria in some specifications, and insufficient granularity of feature strings, leading to implementations misrepresenting the degree of support for a class of features. This specification seeks to remedy that in the context of user agents conforming to DOM Level 3 Events by providing discrete feature strings and clear guidelines for the circumstances under which a user agent must or must not report in a positive manner when queried for support of the feature which that feature string represents.

DOM Level 3 Events introduces compositional feature strings, which are base feature strings combined with extended feature strings, a new mechanism for testing support for each specific feature, rather than relying on modules-level feature strings. A user agent conforming to DOM Level 3 Events must also implement the following feature string convention for describing DOM3 Events feature support:

  • The primary base feature string for DOM Level 3 Events shall be “Events”, with the optional version string “3.0”, indicating that the user agent supports the DOM Level 3 Events Architecture in the manner described in the appropriate conformance section.
    • Since DOM Level 3 Events is built on top of DOM Level 2 Events [DOM2 Events], an implementation that returns true for "Events" and "3.0" shall also return true for the parameters "Events" and "2.0".
    • If the version parameter is omitted, the user agent must not differentiate between the DOM Events Architecture as described in DOM Level 3 Events and DOM Level 2 Events, in terms of reporting support for the features indicated by the base feature string.
  • The extended feature string for each event type defined in DOM Level 3 Events shall be the base feature string “Events”, followed by the period character ("."), followed by the name of that event type, with the optional version string “3.0”, indicating that the user agent supports that specific event type in the manner described in the appropriate conformance section. For example, the feature string for the textInput event would be “Events.textInput”, with the optional version string “3.0”.
    • Because this specification does not retroactively define extended feature strings for DOM Level 2 Events, using the DOMImplementation.hasFeature() method with extended feature strings with a version string “2.0” must return false.Warning! Because this mechanism for discrete feature strings was not defined in earlier DOM Events specifications, older user agents which support those specifications but not this one may report false negatives in terms of supporting particular features. For example, a browser which supports the the click event type as defined in DOM Level 2 Events, but does not support this specification, is likely to return false to the method call document.implementation.hasFeature("Events.click", ""). The content author should not take this for definitive proof that the implementation does not support the click event type, but rather that other means of testing are required in that instance. This method is best used as a means to detect positive results, not negative ones. However, it is expected that this will prove of sufficient utility in many cases to justify its use.
    • A user agent which supports an event type in a manner conforming to DOM Level 2 Events but not conforming to DOM Level 3 Events must not report a positive result to that extended feature string, regardless of the value of the version string.
    • A specification or host language which conforms to DOM Level 3 Events, and which extends this specification in a manner consistent with the extension conformance criteria, may define extended feature strings for event types defined in that specification. These extended feature strings may be used with the feature string “Events”.

      Example: Support for the SVG zoom event type might be tested using the method call document.implementation.hasFeature("Events.zoom", "")

  • For backwards compatibility, each interface defined in DOM Level 3 Events also has a feature string, which may act as a base feature string or as an extended feature string. If used as a base feature string, it must follow the conventions of the primary base feature string (e.g., “KeyboardEvent”, with the optional version string “3.0”); if used as an extended feature string, it must follow the conventions of the extended feature strings for event types (e.g., “Events.KeyboardEvent”, with the optional version string “3.0”). In either case, the user agent must only report a positive result if it supports that specific interface and all associated event types in the manner described in the appropriate conformance section. Warning! because this is not as specific as testing for a specific event type and may thus be less likely to be accurate, content authors are encouraged to use the feature strings for event types rather than interfaces.

Warning! This specification does not provide a means to guarantee that any given element of a host language is capable of generating or dispatching an event of any given event type (e.g., an HTML 'img' element may not dispatch a textInput event), or what the attributes of that event will be beyond those defined in this specification (e.g., the host language may add attributes to the event object). A host language may provide a different means to do so, including its own relevant feature strings.

1.4 Stylistic Conventions

The following stylistic conventions are followed in this specification, per the Proposed W3C Specification Conventions:

'This is a keyword or value'

This is an event type

This is a link to a definition in the glossary

This is a note.

This is a warning. It is used on security notes and to mark deprecated features.

This is an example.

This is a feature at risk, which is likely to be removed from the specification.

This is a proposed new feature.

Issue: This is an open issue.

Feedback on features at risk, new features, and open issues is especially appreciated.

In addition, certain terms are used in this specification with particular meanings. The term “implementation” applies to a browser, content authoring tool, or other user agent that implements this specification, while a content author is a person who writes script or code that takes advantage of the interfaces, methods, attributes, events, and other features described in this specification in order to make Web applications, and a user is the person who uses those Web applications in an implementation.

2. Glossary

Some of the following term definitions have been borrowed or modified from similar definitions in other W3C or standards documents. See the links within the definitions for more information.

activation behavior
The action taken when an event, typically initiated by users through an input device, causes an element to fulfill a defined task. The task may be defined for that element by the host language, or by author-defined variables, or both. The default task for any given element may be a generic action, or may be unique to that element. For example, the activation behavior of an HTML or SVG <a> element shall be to cause the user agent to traverse the link specified in the href attribute, with the further optional parameter of specifying the browsing context for the traversal (such as the current window or tab, a named window, or a new window); the activation behavior of an HTML <input> element with the type attribute value submit shall be to send the values of the form elements to an author-defined IRI by the author-defined HTTP method. See Activation triggers and behavior for more details.
activation trigger
An event which is defined to initiate an activation behavior. Refer to Activation triggers and behavior for more details.
author
In the context of this specification, an author, content author, or script author is a person who writes script or other executable content that uses the interfaces, events, and event flow defined in this specification. See Content authors and content conformance category for more details.
bubbling phase
The process by which an event can be handled by one of the target ancestors after being handled by the proximal event target. See the description of the bubble phase in the context of event flow for more details.
capture phase
The process by which an event can be handled by one of the target ancestors before being handled by the proximal event target. See the description of the capture phase in the context of event flow for more details.
character value
In the context of key values, a character value is a string representing one or more Unicode characters, such as a letter or symbol, or a set of letters. Note: in source code, some key values, such as non-graphic characters, may be represented using the character escape syntax of the programming language in use.
dead key
A dead key is a key or combination of key that produces no character by itself, but which in combination or sequence with another key produces a modified character, such as a character with diacritical marks (e.g. ö, é, â).
default action
A default action is an optional supplementary behavior that an implementation must perform in combination with the dispatch of the event object. Each event type definition, and each specification, defines the default action for that event type, if it has one. An instance of an event may have more than one default action under some circumstances, such as when associated with an activation trigger. A default action may be cancelled through the invocation of the Event.preventDefault() method. For more details, see Default actions and cancelable events.
defaultView
The defaultView is an object which implements the AbstractView interface of the Document's DocumentView interface, which serves as a reference to the containing frame or window. This interface may also be accessed as the Window interface in many implementations.
delta
The distance an input device using the WheelEvent interface (such as a mouse wheel) has rotated around its axis. The value of a delta shall be a integer indicating a distance, measured as the number of rolls the wheel has been rotated. A positive value shall indicate that the wheel has been rotated towards the user on vertically-aligned devices or in a right-hand manner on horizontally-aligned devices, and a negative value shall indicate that the wheel has been rotated away from the user on vertically-aligned devices or in a left-hand manner on horizontally aligned devices. The default value of a delta attribute shall be 0.
deprecated
Features marked as deprecated are included in the specification as reference to older implementations or specifications, but are optional and discouraged. Only features which have existing or in-progress replacements shall be deprecated in this specification. Implementations which do not already include support for the feature may implement deprecated features for reasons of backwards compatibility with existing content, but content authors creating content should not use deprecated features, unless there is no other way to solve a use case. Other specifications which reference this specification should not use deprecated features, but should point instead to the replacements of which the feature is deprecated in favor. Features marked as deprecated in this specification are expected to be dropped from future specifications.
dispatch
To create an event with attributes and methods appropriate to its type and context, and propagate it through the DOM tree in the specified manner. Interchangeable with the term “fire", e.g. “fire a 'click' event” or “dispatch a 'load' event”.
document
An object instantiating the Document interface [DOM3 Core], representing the entire HTML or XML text document. Conceptually, it is the root of the document tree, and provides the primary access to the document's data.
DOM application
A DOM application is script or code, written by a content author or automatically generated, which takes advantage of the interfaces, methods, attributes, events, and other features described in this specification in order to make dynamic or interactive content, such as Web applications, exposed to users in a user agent.
DOM Level 0
The term “DOM Level 0” refers to a mix of HTML document functionalities, often not formally specified but traditionally supported as de facto standards, implemented originally by Netscape Navigator version 3.0 or Microsoft Internet Explorer version 3.0. In many cases, attributes or methods have been included for reasons of backward compatibility with “DOM Level 0”.
empty string
The empty string is a value of type DOMString of length 0, i.e. a string which contains no characters (neither printing nor control characters).
event
An event is the representation of some occurrence (such as a mouse click on the presentation of an element, the removal of child node from an element, or any number of other possibilities) which is associated with its proximal event target. Each event is an instantiation of one specific event type.
event order
The sequence in which events from the same event source or process occur, using the same or related event interfaces. For example, in an environment with a a mouse, a track pad, and a keyboard, each of those input devices would constitute a separate event source, and each would follow its own event order; a mousedown event from the trackpad, followed by a mouseup event from the mouse would not result in a click event. Note that there may be interactions between different event orders; for example, a click event may be modified by a concurrent keypress event (shift+click); however, the event orders of these different event sources would be distinct. The event order of some interfaces are device-independent; for example, a user may change focus using the 'Tab' key, or by clicking the new focused element with the mouse. The event order in such cases depends on the state of the process, not on the state of the device that initiates the state change.
event phase
See phase.
event target
The object to which an event is targeted.
event type
The name of an event object which defines particular trigger conditions and other characteristics which distinguish it from other event types. For example, the click event type has different characteristics than the mouseover or load event types. The event type is exposed as the the Event.type attribute on the event object. See event types for more details. Also loosely referred to as 'event', such as the click event.
focus
Focus is a special state of receptivity and concentration on an particular element or other event target within a document. Each element has different behavior when focused, depending on its functionality, such as priming the element for activation (as for a button or hyperlink) or toggling state (as for a checkbox), receiving text input (as for a text form field), or copying selected text. For more details, see Document Focus and Focus Context.
focus ring
A focus ring is a an ordered set of focus targets within a document. A host language may define one or more ways to determine the order of targets, such as document order, a numerical index defined per focus target, explicit pointers between focus targets, or a hybrid of different models. Each document may contain multiple focus rings, or conditional focus rings. Typically, for document-order or indexed focus rings, focus “wraps around” from the last focus target to the first.
fire
A synonym for dispatch.
host language
Any language which integrates the features of another language or API specification, while normatively referencing the origin specification rather than redefining those features, and extending those features only in ways defined by the origin specification. An origin specification typically is only intended to be implemented in the context of one or more host languages, not as a standalone language. For example, XHTML, HTML, and SVG are host languages for DOM 3 Events, and they integrate and extend the objects and models defined in this specification.
hysteresis
A feature of human interface design to accept input values within a certain range of location or time, in order to improve the user experience. For example, allowing for small deviation in the time it takes for a user to double-click a mouse button is temporal hysteresis, and no immediately closing a nested menu if the user mouses out from the parent window when transitioning to the child menu is locative hysteresis.
IME
input method editor
An input method editor (IME), also known as a front end processor, is an application that performs the conversion between keystrokes and ideographs or other characters, usually by user-guided dictionary lookup, often used in East Asian languages (e.g. Chinese, Japanese, Korean). An IME may also be used for dictionary-based word completion, such as on mobile devices. See Input Method Editors for treatment of IMEs in this specification. See also text composition system.
key value
A key value is character value or multi-character string (such as 'Enter', 'Tab', or 'MediaNextTrack') associated with a key in a particular state. Control keys, function keys, modifier keys, dead keys, and others keys always have a key value, whether or not it has a character value.
local name
See local name in [XML Namespaces 1.0].
namespace URI
A namespace URI is a URI that identifies an XML namespace. This is called the namespace name in [XML Namespaces 1.0]. See also sections 1.3.2 "DOM URIs" and 1.3.3 "XML Namespaces" regarding URIs and namespace URIs handling and comparison in the DOM APIs.
phase
In the context of events, a phase is set of logical traversals from node to node along the DOM tree, from the defaultView (window), to the Document object, root element down to the event target (capture phase), at the event target itself (target phase), and back up to the same chain (bubbling phase).
propagation path
The ordered set of event targets though which an event object will pass sequentially on the way to and back from the proximal event target. As the event propagates, each event target in the propagation path shall in turn be set as the Event.currentTarget. The propagation path is initially comprised of one or more event phases as defined by the event type, but may be interrupted. Also known as an event target chain.
proximal event target
The proximal event target is the object representing the event target to which an event is targeted using the DOM event flow. The proximal event target is the value of the Event.target attribute.
QWERTY
QWERTY (pronounced "ˈkwɜrti") is a common keyboard layout, so named because the first five character keys on the top row of letter keys are Q, W, E, R, T, and Y. There are many other popular keyboard layouts (including the Dvorak layout), most designed for localization or ergonomics.
roll
A unit of rotation for an input device using the WheelEvent interface. On some devices this may be a finite physical step. On devices with smooth rotation, a roll becomes the smallest reported amount of rotation.
root element
The first element node of a document, of which all other elements are children; the document element.
rotation
An indication of incremental change on an input device using the WheelEvent interface. On some devices this may be a literal rotation of a wheel, while on others, it may be movement along a flat surface, or pressure on a particular button.
text composition system
A software component which interprets some form of alternate input, such as a input method editor, a speech processor, or a handwriting recognition system, and converts it to text.
target phase
The process by which an event can be handled by the proximal event target. See the description of the target phase in the context of event flow for more details.
topmost event target
The topmost event target shall be the element highest in the rendering order which is capable of being an event target. In this case, 'top' shall refer not to the position on the screen, but the logical order of the element in relation to other elements in drawing or stacking order on the z-axis (where the x-axis is the screen width and the y-axis is the screen height). In HTML and CSS, or in SVG, this is controlled by the document order, as modified in HTML and CSS by the 'z-index' property. In some cases, such as when using some values of the SVG 'pointer-events' property, the topmost element may not receive pointer events, in which case, the next element in z-index order which can receive pointer-events is the topmost event target. Note that visibility of the element does not necessarily affect its ability to be the topmost event target, since an element which is hidden by use of the CSS 'visibility' property can still receive pointer events (though not one with a 'display' property of none), and the topmost event target may be completely obscured by another element which cannot receive pointer events. Unless otherwise noted, there is only one topmost event target in any event. For specific details regarding hit testing and stacking order, refer to the host language.
tree
A data structure that represents a document as a hierarchical set of nodes with child-parent-sibling relationships, i.e. each node having one or more possible ancestors (nodes higher in the hierarchy in a direct lineage), one or more possible descendants (nodes lower in the hierarchy in a direct lineage), and one or more possible peers (nodes of the same level in the hierarchy, with the same immediate ancestor).
Unicode character categories
The Unicode character categories, a subset of the complete Unicode general categories, comprise the categories Ll, Lm, Lo, Lt, Lu, Nd, Nl, No, Pc, Pd, Pe, Pf, Pi, Po, Ps, Sc, Sk, Sm, and So.
Unicode code point
A Unicode code point is a unique hexadecimal number signifying a character by its index in the Unicode codespace (or library of characters). In the context of key values, a Unicode code point is expressed as a string in the format “\u” followed by a hexadecimal character index in the range 0000 to 10FFFF, using at least four digits. See also character value.
user agent
A program, such as a browser or content authoring tool, normally running on a client machine, which acts on a user's behalf in retrieving, interpreting, executing, presenting, or creating content conforming to a specification. Users may act on the content using different user agents at different times, for different purposes. See the Web browsers and other dynamic or interactive user agents and Authoring tools conformance categories for more details.

3. DOM Event Architecture

3.1 Event dispatch and DOM event flow

This section defines the event dispatch mechanism of the event model defined in this specification. Applications may dispatch event objects using the EventTarget.dispatchEvent() method, and implementations must dispatch event objects as if through this method. The behavior of this method depends on the event flow associated with the underlying object. An event flow describes how event objects propagate through a data structure. As an example, when an event object is dispatched to an element in an XML document, the object propagates through parts of the document, as determined by the DOM event flow which is defined at the end of this section.

graphical representation of an event dispatched in a DOM tree using the DOM event flow

Figure 1: graphical representation of an event dispatched in a DOM tree using the DOM event flow

Event objects are always dispatched to the proximal event target. At the beginning of the dispatch, implementations must first determine the event object's propagation path. The propagation path shall be an ordered list of event targets through which the event object must pass. The last item in the list shall be the proximal event target; the preceding items in the list are referred to as the target's ancestors, and the immediately preceding item as the target's parent. Once determined, the propagation path must not be changed, even if an element in the propagation path is moved within the DOM or removed from the DOM. As an example, in the DOM event flow event listeners might change the position of the proximal event target in the document while the event object is being dispatched; such changes do not affect the propagation path.

As the next step, the event object must complete one or more event phases. This specification defines three event phases: capture phase; target phase; and bubble phase. Event objects complete these phases in the specified order using the partial propagation paths as defined below. A phase shall be skipped if it is not supported, or if the event object's propagation has been stopped. For example, if the Event.bubbles attribute is set to false, the bubble phase shall be skipped, and if Event.stopPropagation() has been called prior to the dispatch, all phases must be skipped.

  1. The capture phase: the event object must propagate through the target's ancestors from the defaultView to the target's parent. This phase is also known as the capturing phase. Event listeners registered for this phase must handle the event before it reaches its target.
  2. The target phase: the event object must arrive at the event object's proximal event target. This phase is also known as the at-target phase. Event listeners registered for this phase must handle the event once it has reached its target. If the event type indicates that the event must not bubble, the event object must halt after completion of this phase.
  3. The bubble phase: the event object propagates through the target's ancestors in reverse order, starting with the target's parent and ending with the defaultView. This phase is also known as the bubbling phase. Event listeners registered for this phase shall handle the event after it has reached its target.

Implementations must let event objects accomplish an event phase by applying the following steps while there are pending event targets in the partial propagation path for this phase and the event object's propagation has not been stopped through Event.stopPropagation().

First, the implementation must determine the current target. This shall be the next pending event target in the partial propagation path, starting with the first. From the perspective of an event listener this shall be the event target the listener has been registered on.

Next, the implementation must determine the current target's candidate event listeners. This shall be the list of all event listeners that have been registered on the current target in their order of registration. Once determined, the candidate event listeners cannot be changed; adding or removing listeners does not affect the current target's candidate event listeners.

Finally, the implementation must process all candidate event listeners in order and trigger each listener if all the following conditions are met:

An implementation shall trigger a listener by invoking the EventListener.handleEvent() method or an equivalent binding-specific mechanism.

As the final step of the event dispatch, for reasons of backwards compatibility, the implementation must reset the event object's internal-propagation and default-action-prevention states. This ensures that an event object may be properly dispatched multiple times while also allowing to prevent the event objects propagation or default actions prior to the event dispatch.

In the production of the propagation path, if the defaultView implements the EventTarget interface, the event propagates from defaultView to the document object during the capture phase, and from the document object to the defaultView during the bubble phase. Note: for legacy reasons, the load event does not propagate to the defaultView in HTML implementations.

The model defined above must be applied regardless of the specific event flow associated with an event target. Each event flow must define how the propagation path shall be determined and which event phases are supported. The DOM event flow is an application of this model: the propagation path for a Node object shall be determined by its Node.parentNode chain, and if applicable, the document's containing defaultView; all events accomplish the capture and target phases; whether an event accomplishes the bubble phase shall be defined individually for each event type. An alternate application of this model can be found in [DOM3 Load and Save].

Implementations of the DOM event model must be reentrant. Event listeners may perform actions that cause additional events to be dispatched. Such events are handled in a synchronous manner, the event propagation that causes the event listener to be triggered must resume only after the event dispatch of the new event is completed.

3.2 Default actions and cancelable events

Event objects may have one or more default actions associated with them. These are actions the implementation must perform in combination with the dispatch of the event object. An example is the [HTML5] form element. When the user submits the form (e.g. by pressing on a submit button), the HTML event submit should be dispatched to the element and the default action for this event type shall be generally to send a request to a Web server with the parameters from the form.

Default actions should be performed after the event dispatch has been completed, but in exceptional cases also immediately before the event is dispatched.

Issue: insert example here: <input type="checkbox">'s .checked handling comes to mind. .checked is changed just before 'click' event is dispatched, and if default action is prevented, .checked is set to its original value.

Some event objects are cancelable, meaning the default action can be prevented from occuring, or, if the default action is carried out before the dispatch, its effect may be reversed. Whether an event object is cancelable shall be indicated by the Event.cancelable attribute. Event listeners can cancel default actions of cancelable event objects by invoking the Event.preventDefault() method, and determine whether an event has been canceled through the Event.defaultPrevented attribute while the object is being dispatched, or from the return value of the EventTarget.dispatchEvent() method for event objects dispatched by the DOM application itself.

This specification does not offer features to programatically query if an event object has any default action associated with it, or to associate new default actions to an event object. Other specifications may define what default actions, if any, are associated with certain event objects. Further, implementations may associate default actions with events as necessary and appropriate for that implementation. As an example, one implementation may scroll a document view by a certain amount as default action of a mouse wheel event, while another implementation may instead zoom the document as its default action for a mouse wheel event.

3.3 Synchronous and asynchronous events

Events may occur either synchronously ("sync") or asynchronously ("async").

Events which are synchronous must be treated as if they are in a virtual queue in a first-in-first-out model, ordered by sequence of temporal occurrence, with respect to other events, to changes in the DOM, and to user interaction. Each event in this virtual queue must be delayed until the previous event has completed its propagation behavior, or been canceled. Some sync events are driven by a specific device or process, such as mouse button events; these events are governed by the event order algorithms defined for that set of events, and a user agent must dispatch these events in the defined order.

Example: A user double-clicks a passage of text to select a word, then presses the 'delete' key to erase the word, triggering the following synchronous sequence of events: mousedown, mouseup, click, mousedown, mouseup, click, dblclick, select, keydown, DOMCharacterDataModified. Each of these events are fired in the sequence initiated by the user's actions.

Events which are asynchronous may be dispatched as the results of the action are completed, with no relation to other events, to other changes in the DOM, nor to user interaction.

Example: To Do: Create good example of async events.

3.3.1 Event order and event loops

Most events take place in a sequential context. HTML5 [HTML5] defines its event operations in terms of an event loop mechanism, in which events of all types are fed into different task queues. This specification does not define events in terms of this event loop mechanism, but it is compatible with this mechanism. Instead, this specification defines several operation-specific event orders.

Using the terminology of HTML5, each independent device, such as a mouse or keyboard, should be treated as a task source which feeds into the appropriate task queue, in the order defined by the event order associated with that device; each operation, such as a focus change or composition input, also acts as a task source for the appropriate task queue. The resolution of these event loops is handled in a manner conforming to the host language, such as HTML [HTML5].

Warning! Certain events, such as “hotkeys” or controls keys pressed in a certain sequence, may be “swallowed” by the operating system or the application, interrupting the expected event order. Content authors should make appropriate checks for such occurrences.

3.4 Trusted events

Events which are generated by the user agent, either as a result of user interaction, or as a direct result of changes to the DOM, are trusted by the user agent with privileges that are not afforded to events generated by script through the DocumentEvent.createEvent("Event") method, modified using the Event.initEvent() method, or dispatched via the EventTarget.dispatchEvent() method. The trusted attribute of trusted events has a value of true, while untrusted events have a trusted attribute value of false.

Most untrusted events should not trigger default actions, with the exception of click or DOMActivate events which have been synthesized and are managed by the user agents event as the default action of an activation trigger (see Activation triggers and behavior for more details); these user-agent-managed synthesized events have a have a trusted attribute value of false, but still initiate any default actions. All other untrusted events must behave as if the Event.preventDefault() method had been called on that event.

For security reasons, a host language should not define events which are not cancelable (see Default actions and cancelable events), but also have default actions, since these default actions may be initiated by untrusted events.

3.5 Activation triggers and behavior

Certain proximal event targets (such as a link or button element) may have associated activation behavior (such a following a link) that implementations perform in response to an activation trigger (such as clicking a link).

A host language should indicate which, if any, elements have activation behavior, describe appropriate activation triggers, and define the result of that activation behavior. An implementation which supports a host language should initiate these activation behavior when the associated activation trigger occurs.

Example: Both HTML and SVG have an a element which indicates a link. Relevant activation triggers for an a element are a click event on the text or image content of the a element, or a keydown event with a key attribute value of 'Enter' key when the a element has focus. The activation behavior for an a element is normally to change the content of the window to the content of the new document, in the case of external links, or to reposition the current document relative to the new anchor, in the case of internal links.

An activation trigger is a user action or an event which indicates to the implementation that an activation behavior should be initiated. User-initiated activation triggers include clicking a mouse button on an activatable element, pressing the 'Enter' key when an activatable element has focus, or pressing a key that is somehow linked to an activatable element (a “hotkey” or “access key”) even when that element does not have focus. Event-based activation triggers may include timer-based events that activate an element at a certain clock time or after a certain time period has elapsed, progress events after a certain action has been completed, or many other condition-based or state-based events.

In some cases, a host language may define attributes or even attribute values which add to or change the native activation trigger or activation behavior of an element. For example, ARIA [ARIA] defines values for the role attribute that add semantics to the element to which it is applied, for purposes of enhanced accessibility. In such cases, if the host language does not explicitly define the activation trigger or activation behavior, the content author must provide the mechanics of the activation trigger (via an event listener) or activation behavior (such as calling an ECMAScript function) for that element when applying that attributes or attribute value.

3.5.1 Activation event synthesis

If the instance of the activation trigger is not an event of event type click (that is, when it does not result from a user activating a button or link using a mouse or equivalent pointing device), the implementation must synthesize and dispatch an event of event type click as one of the default actions of that activation trigger; the value of the Event.target must be set to the proximal event target (normally, the currently focused element), and the event must simulate a left click (i.e. the MouseEvent.button attribute value must be 0, and the MouseEvent.buttons attribute value must be 1). Other context information of such a simulated click event is implementation dependent, but for historical purposes, the interface for the click event must be the MouseEvent interface, regardless of the actual device used to activate the element. Preventing the default action of the activation trigger, such as with the Event.preventDefault(), must stop the initiation of the activation behavior.

Example: When a user activates a hyperlink using a keyboard, such as by focusing the hyperlink element and pressing the 'Enter' or 'Space' key, a click event would be dispatched as the default action of the respective keydown event.

Implementations must dispatch the synthesized click event as described above even if they do not normally dispatch such an event (e.g. when activation is requested by a voice command, since this specification does not address event types for voice input).

Note: The activation of an event target is device dependent, but is also application dependent, e.g. a link in a document can be activated using a mouse click or a mouse double click.

Implementations which support the DOMActivate event type should also dispatch a DOMActivate event as a default action of a click event which is associated with an activation trigger. However, such implementations should only initiate the associated activation behavior once for any given occurrence of an activation trigger.

Example: The DOMActivate event type is required to be supported for XForms [XFORMS], which is intended for implementation within a host language. In a scenario where a plugin or script-based implementation of XForms is intended for installation in a native implementation of this specification which does not support the DOMActivate event type, the XForms user agent must synthesize and dispatch its own DOMActivate events based on the appropriate activation triggers. Thus, when a click event is dispatched by the DOM Level 3 Events user agent, the XForms user agent must determine whether to synthesize a DOMActivate event with the same relevant properties as a default action of that click event; appropriate cues may be whether the click event is trusted, or whether its proximal event target has a DOMActivate event listener registered.

Note: Content authors should not rely upon the interoperable support of DOMActivate in many user agents. Thus, content authors may use the DOMActivate event type whenever they wish to make or react to an activation trigger, but should use the click event type for more accessible behavior instead, due to wider implementation.

Warning! The DOMActivate event type is deprecated in this specification.

3.5.1 Activation Event Order

Activation triggers and behavior can be defined in part by the events which are dispatched in a set order relative to one another. The following is the typical sequence of events for an element activated by a pointing device (with only pertinent events listed):

  1. click
  2. DOMActivate (default action, if supported by the user agent; synthesized; trusted="false")
  3. All other default actions, including the activation behavior

The following is the typical sequence of events when a focused element is activated by a key event (with only pertinent events listed):

  1. keydown (must be a key which can activate the element, such as the 'Enter' or 'Space' key, or the element is not activated)
  2. click (default action; synthesized; trusted="false")
  3. DOMActivate (default action, if supported by the user agent; synthesized; trusted="false")
  4. All other default actions, including the activation behavior

4. Basic Event Interfaces

The interfaces described in this section are fundamental to DOM Level 3 Events and must always be supported by the implementation. Together they define the feature Events 3.0.

The event types defined in this specification derive from these basic interfaces, and shall inherit all of the attributes, methods, and constants of the interfaces they derive from. Event types defined in other specifications may similarly inherit from these basic interfaces or other interfaces defined in this specification, or may define their own interfaces. The following chart describes the inheritance structure of interfaces defined in this specification.

graphical representation of the DOM3 Events interface inheritance

Figure 2: graphical representation of the DOM3 Events interface inheritance

4.1 Interface Event

Interface Event (introduced in DOM Level 2)

The Event interface is used to provide contextual information about an event to the listener processing the event. An object which implements the Event interface shall be passed as the parameter to an EventListener. The object passed to the event listener may also implement derived interfaces that provide access to information directly relating to the type of event they represent.

To create an instance of the Event interface, use the DocumentEvent.createEvent("Event") method call.


IDL Definition

// Introduced in DOM Level 2:
interface Event {

  // PhaseType
  const unsigned short               CAPTURING_PHASE      = 1;
  const unsigned short               AT_TARGET            = 2;
  const unsigned short               BUBBLING_PHASE       = 3;

  readonly attribute DOMString       type;
  readonly attribute EventTarget     target;
  readonly attribute EventTarget     currentTarget;
  readonly attribute unsigned short  eventPhase;
  readonly attribute boolean         bubbles;
  readonly attribute boolean         cancelable;
  readonly attribute DOMTimeStamp    timeStamp;
  void                               stopPropagation();
  void                               preventDefault();
  void                               initEvent(in DOMString eventTypeArg, 
                                               in boolean canBubbleArg, 
                                               in boolean cancelableArg);
  // Introduced in DOM Level 3:
  void                               stopImmediatePropagation();
  readonly attribute boolean         defaultPrevented;
  readonly attribute boolean         trusted;
};
                
Definition group PhaseType

An integer indicating which phase of the event flow is being processed as defined in Event dispatch and DOM event flow.

Defined Constants
AT_TARGET
The current event is in the target phase, i.e. it is being evaluated at the proximal event target.
BUBBLING_PHASE
The current event phase is the bubbling phase.
CAPTURING_PHASE
The current event phase is the capture phase.
Attributes
bubbles of type boolean, readonly

Used to indicate whether or not an event is a bubbling event. If the event can bubble the value shall be true, otherwise the value shall be false.

cancelable of type boolean, readonly

Used to indicate whether or not an event can have its default action prevented (see also Default actions and cancelable events). If the default action can be prevented the value shall be true, otherwise the value shall be false.

currentTarget of type EventTarget, readonly

Used to indicate the EventTarget whose EventListeners are currently being processed. This is particularly useful during the capture and bubbling phases. When used with the Event dispatch and DOM event flow, this attribute contains the proximal event target or a target ancestor.

defaultPrevented of type boolean, readonly, introduced in DOM Level 3

Used to indicate whether Event.preventDefault() has been called for this event.

trusted of type boolean, readonly, introduced in DOM Level 3

Used to indicate whether this event was generated by the user agent (trusted) or by script (untrusted). See trusted events for more details.

eventPhase of type unsigned short, readonly

Used to indicate which phase of event flow is currently being accomplished.

target of type EventTarget, readonly

Used to indicate the event target. This attribute contains the proximal event target when used with the Event dispatch and DOM event flow.

timeStamp of type DOMTimeStamp, readonly

Used to specify the time at which the event was created in milliseconds relative to 1970-01-01T00:00:00Z. Due to the fact that some systems may not provide this information the value of timeStamp may be not available for all events. When not available, the value shall be 0.

type of type DOMString, readonly

The name of the event type. The name must be a DOMString. Specifications that define events, content authors, and authoring tools must use case-sensitive event type names that do not contain whitespace characters.

Methods
initEvent

Initializes attributes of an Event created through the DocumentEvent.createEvent method. This method may only be called before the Event has been dispatched via the EventTarget.dispatchEvent() method. If the method is called several times before invoking EventTarget.dispatchEvent, only the final invocation takes precedence. This method has no effect if called after the event has been dispatched. If called from a subclass of the Event interface only the values specified in this method are modified, all other attributes are left unchanged.

This method sets the Event.type attribute to eventTypeArg.

Warning! For security reasons, events modified using Event.initEvent() must have a trusted attribute value of false. See trusted events for more details.

Parameters
eventTypeArg of type DOMString

Specifies Event.type, the name of the event type.

canBubbleArg of type boolean

Specifies Event.bubbles. This parameter overrides the intrinsic bubbling behavior of the event.

cancelableArg of type boolean

Specifies Event.cancelable. This parameter overrides the intrinsic cancelable behavior of the event.

No Return Value
No Exceptions
preventDefault
When this method is evoked, the event must be canceled, meaning any default actions normally taken by the implementation as a result of the event must not occur (see also Default actions and cancelable events). Calling this method for a non-cancelable event shall have no effect. If an event has more than one default action, each cancelable default action must be canceled.

Note: This method does not stop the event propagation; use Event.stopPropagation() or Event.stopImmediatePropagation() for that effect.

No Parameters
No Return Value
No Exceptions
stopImmediatePropagation introduced in DOM Level 3
Prevents other event listeners from being triggered and, unlike Event.stopPropagation() its effect shall be immediate . Once it has been called, further calls to this method have no additional effect.

Note: This method does not prevent the default action from being invoked; use Event.preventDefault() for that effect.

No Parameters
No Return Value
No Exceptions
stopPropagation
Prevents other event listeners from being triggered but its effect shall be deferred until all event listeners attached on the Event.currentTarget have been triggered. Once it has been called, further calls to this method have no additional effect.

Note: This method does not prevent the default action from being invoked; use Event.preventDefault() for that effect.

No Parameters
No Return Value
No Exceptions

4.2 Interface CustomEvent

Interface CustomEvent (introduced in DOM Level 3)

The CustomEvent interface is the recommended interface for application-specific event types. Unlike the Event interface, it allows applications to provide contextual information about the event type. Application-specific event types should use a prefix string on the event type name to avoid clashes with future general-purpose event types.

To create an instance of the CustomEvent interface, use the DocumentEvent.createEvent("CustomEvent") method call.


IDL Definition

// Introduced in DOM Level 3:
interface CustomEvent : Event {
  readonly attribute DOMObject         detail;
  void               initCustomEvent(in DOMString typeArg, 
                                     in boolean canBubbleArg, 
                                     in boolean cancelableArg, 
                                     in DOMObject detailArg);
};
                
Attributes
detail of type DOMObject, readonly

Specifies some detail information about the Event.

Methods
initCustomEvent
Initializes attributes of a CustomEvent object. This method has the same behavior as Event.initEvent().
Parameters
typeArg of type DOMString

Refer to the Event.initEvent() method for a description of this parameter.

canBubbleArg of type boolean

Refer to the Event.initEvent() method for a description of this parameter.

cancelableArg of type boolean

Refer to the Event.initEvent() method for a description of this parameter.

detailArg of type DOMObject

Specifies CustomEvent.detail. This value may be null.

No Return Value
No Exceptions

4.3 Interface EventTarget

Interface EventTarget (introduced in DOM Level 2)

The EventTarget interface must be implemented by all the objects which could be event targets in an implementation which supports an event flow. The interface allows registration and removal of event listeners, and dispatch of events to an event target.

Note: Though an event listener can be registered for any event target node, the user agent only dispatches UA-generated (trusted) events on node types that are defined as proximal event target types for that specific event type (see the List of DOM3 Event Types); for example, a mouseover event type registered on a text node will never be fired by the user agent, though a content author could dispatch an event of that type on the text node via script.

When used with the DOM event flow, this interface must be implemented by all proximal event targets and target ancestors, i.e. all DOM Nodes of the tree support this interface when the implementation conforms to DOM Level 3 Events and, therefore, this interface can be obtained by using binding-specific casting methods on an instance of the Node interface.

Invoking addEventListener repeatedly on the same EventTarget with the same values for the parameters type, listener, and useCapture has no effect. Doing so does not cause the EventListener to be called more than once and does not cause a change in the triggering order.

Note: In addition to the EventTarget.addEventListener method, some host languages may allow a content author to register event listeners by the use of attributes, e.g. onclick="handleClick()". Because the details of this are often language-specific, this type of event listener registration is not defined in this specification, but in general, any event type may be used as an attribute in this way by adding the prefix on- to the event type name, and events so dispatched should behave consistently with the event registration and propagation defined in this specification, with the same interfaces, properties, and methods.


IDL Definition

// Introduced in DOM Level 2:
interface EventTarget {
  void               addEventListener(in DOMString type, 
                                      in EventListener listener, 
                                      in boolean useCapture);
  void               removeEventListener(in DOMString type, 
                                         in EventListener listener, 
                                         in boolean useCapture);
  // Modified in DOM Level 3:
  boolean            dispatchEvent(in Event evt)
                                   raises(EventException, 
                                   DOMException);
                                   
};
                
Methods
addEventListener
Registers an event listener, depending on the useCapture parameter, on the capture phase of the DOM event flow or its target and bubbling phases.
Parameters
type of type DOMString

Specifies the Event.type associated with the event for which the user is registering.

listener of type EventListener

The listener parameter takes an object implemented by the user which implements the EventListener interface and contains the method to be called when the event occurs.

useCapture of type boolean

If true, useCapture indicates that the user wishes to add the event listener for the capture phase and target only, i.e. this event listener will not be triggered during the bubbling phase. If false, the event listener must only be triggered during the target and bubbling phases.

No Return Value
No Exceptions
dispatchEvent modified in DOM Level 3
Dispatches an event into the implementation's event model. The event target of the event shall be the EventTarget object on which dispatchEvent is called.

Warning! For security reasons, events dispatched using EventTarget.dispatchEvent() must have a trusted attribute value of false. See trusted events for more details.

Parameters
evt of type Event

The event to be dispatched.

Return Value

boolean

Indicates whether any of the listeners which handled the event called Event.preventDefault(). If Event.preventDefault() was called the returned value shall be false, else it shall be true.

Exceptions

EventException

UNSPECIFIED_EVENT_TYPE_ERR: Raised if the Event.type was not specified by initializing the event before dispatchEvent was called. Specification of the Event.type as null or an empty string must also trigger this exception.

DISPATCH_REQUEST_ERR: Raised if the Event object is already being dispatched.

DOMException

NOT_SUPPORTED_ERR: Raised if the Event object has not been created using DocumentEvent.createEvent().

INVALID_CHARACTER_ERR: Raised if Event.type is not a DOMString as conforming to the restrictions in Event.type.

removeEventListener
Removes an event listener. Calling removeEventListener with arguments which do not identify any currently registered EventListener on the EventTarget has no effect.
Parameters
type of type DOMString

Specifies the Event.type for which the user registered the event listener.

listener of type EventListener

The EventListener to be removed.

useCapture of type boolean

Specifies whether the EventListener being removed was registered for the capture phase or not. If a listener was registered twice, once for the capture and target phases and once for the target and bubbling phases, each must be removed separately. Removal of an event listener registered for the capture and target phases does not affect the same event listener registered for the target and bubbling phases, and vice versa.

No Return Value
No Exceptions

4.4 Interface EventListener

Interface EventListener (introduced in DOM Level 2)

The EventListener interface is the primary way for handling events. Users shall implement the EventListener interface and register their event listener on an EventTarget. The users should also remove their EventListener from its EventTarget after they have completed using the listener.

Copying a Node, with methods such as Node.cloneNode or Range.cloneContents, must not copy the event listeners attached to it. Event listeners must be attached to the newly created Node afterwards if so desired.

Moving a Node, with methods Document.adoptNode, Node.appendChild, or Range.extractContents, shall not affect the event listeners attached to it.


IDL Definition

// Introduced in DOM Level 2:
interface EventListener {
  void               handleEvent(in Event evt);
};
                
Methods
handleEvent

This method shall be called whenever an event occurs of the event type for which the EventListener interface was registered.

Parameters
evt of type Event

The Event contains contextual information about the event.

No Return Value
No Exceptions
Exception EventException introduced in DOM Level 2

Event operations may throw an EventException as specified in their method descriptions.


IDL Definition

// Introduced in DOM Level 2:
exception EventException {
  unsigned short          code;
};

// EventExceptionCode
const unsigned short      UNSPECIFIED_EVENT_TYPE_ERR     = 0;
// Introduced in DOM Level 3:
const unsigned short      DISPATCH_REQUEST_ERR           = 1;
                
Definition group EventExceptionCode

An integer indicating the type of error generated.

Defined Constants
DISPATCH_REQUEST_ERR, introduced in DOM Level 3.
If the Event object is already dispatched in the tree.
UNSPECIFIED_EVENT_TYPE_ERR
If the Event.type was not specified by initializing the event before the method was called. Specification of the Event.type as null or an empty string must also trigger this exception.

4.5 Interface DocumentEvent

Interface DocumentEvent (introduced in DOM Level 2)

The DocumentEvent interface provides a mechanism by which the user can create an Event object of a type supported by the implementation. If the feature “Events” is supported by the Document object, the DocumentEvent interface must be implemented on the same object. Language-specific type casting may be required.


IDL Definition

// Introduced in DOM Level 2:
interface DocumentEvent {
  // Modified in DOM Level 3:
  Event                     createEvent(in DOMString eventInterface)
                                        raises(DOMException);
};
                  
Methods
createEvent
Creates an event object of the type specified.
Parameters
eventInterface of type DOMString

The eventInterface parameter specifies the name of the DOM Events interface to be supported by the created event object, e.g. "Event", "MouseEvent", "MutationEvent", and so on. If the Event is to be dispatched via the EventTarget.dispatchEvent() method, the appropriate event initialization method must be called after creation in order to initialize the Event's values.

Example: A content author wishing to synthesize some kind of UIEvent would invoke DocumentEvent.createEvent("UIEvent"). The UIEvent.initUIEvent() method could then be called on the newly created UIEvent object to set the specific type of user interface event to be dispatched, scroll for example, and set its context information, e.g. UIEvent.detail.

For backward compatibility reason, "UIEvents", "MouseEvents", "MutationEvents", and "HTMLEvents" feature names are valid values for the parameter eventInterface and represent respectively the interfaces UIEvent, MouseEvent, MutationEvent, and Event, and the characters 'a'..'z' are considered equivalent to the characters 'A'..'Z'.

If the parameter does not match an event interface name supported by the implementation, the implementation must raise a NOT_SUPPORTED_ERR DOMException

Warning! For security reasons, events generated using DocumentEvent.createEvent("Event") must have a trusted attribute value of false. See trusted events for more details.

Return Value

Event

The newly created event object.

Exceptions

DOMException

NOT_SUPPORTED_ERR: Raised if the implementation does not support the Event interface requested.

4.5.1 Event creation

In most cases, the events dispatched by the DOM Events implementation are also created by the implementation. However, it is possible to simulate events, such as mouse events, by creating the Event objects and dispatch them using the DOM Events implementation.

Creating Event objects that are known to the DOM Events implementation is done using DocumentEvent.createEvent(). The content author must then initialize the Event object by directly setting the Event's property values, by using the generic Event.initEvent() method, or by using any existing event initialization method for that interface, before invoking EventTarget.dispatchEvent(). The Event objects created must be known by the DOM Events implementation; otherwise an event exception shall be thrown.

Example: To Do: Create examples of creating and dispatching an event.

5. Events Module

5.1 Event Types

Each event shall be associated with a type, called event type and available as the type attribute on the event object. The event type must be of type DOMString.

5.1.1 List of DOM3 Event Types

Depending on the level of DOM support, or the devices used for display (e.g. screen) or interaction (e.g., mouse, keyboard, touch screen, or voice), these event types can be generated by the implementation. When used with an [XML 1.0] or [HTML5] application, the specifications of those languages may restrict the semantics and scope (in particular the possible proximal event targets) associated with an event type. Refer to the specification defining the language used in order to find those restrictions or to find event types that are not defined in this document.

The following table provides a non-normative summary of the event types defined in this specification. All events must accomplish the capture and target phases, but not all of them must accomplish the bubbling phase (see also Event dispatch and DOM event flow). Some events are not cancelable (see Default actions and cancelable events). Some events must only be dispatched to a specific set of possible targets in the DOM event flow, specified using node types. Contextual information related to the event type must be accessible using DOM interfaces.

Event Type Sync / Async Bubbling phase Trusted proximal event target types DOM interface Cancelable Default Action
abort Sync No Element Event No none
blur Sync No Element FocusEvent No none
click Sync Yes Element MouseEvent Yes DOMActivate event
compositionstart Sync Yes Element CompositionEvent Yes Launch text composition system
compositionupdate Sync Yes Element CompositionEvent No none
compositionend Sync Yes Element CompositionEvent No none
dblclick Sync Yes Element MouseEvent No none
DOMActivate Sync Yes Element UIEvent Yes none
DOMAttributeNameChanged Sync Yes Element MutationNameEvent No none
DOMAttrModified Sync Yes Element MutationEvent No none
DOMCharacterDataModified Sync Yes Text, Comment, CDATASection, ProcessingInstruction MutationEvent No none
DOMElementNameChanged Sync Yes Element MutationNameEvent No none
DOMFocusIn Sync Yes Element FocusEvent No none
DOMFocusOut Sync Yes Element FocusEvent No none
DOMNodeInserted Sync Yes Element, Attr, Text, Comment, CDATASection, DocumentType, EntityReference, ProcessingInstruction MutationEvent No none
DOMNodeInsertedIntoDocument Sync No Element, Attr, Text, Comment, CDATASection, DocumentType, EntityReference, ProcessingInstruction MutationEvent No none
DOMNodeRemoved Sync Yes Element, Attr, Text, Comment, CDATASection, DocumentType, EntityReference, ProcessingInstruction MutationEvent No none
DOMNodeRemovedFromDocument Sync No Element, Attr, Text, Comment, CDATASection, DocumentType, EntityReference, ProcessingInstruction MutationEvent No none
DOMSubtreeModified Sync Yes defaultView, Document, DocumentFragment, Element, Attr MutationEvent No none
error Async No Element Event No none
focus Sync No Element FocusEvent No none
focusin Sync Yes Element FocusEvent No none
focusout Sync Yes Element FocusEvent No none
keydown Sync Yes Element KeyboardEvent Yes Varies: textInput event; launch text composition system; blur and focus events; DOMActivate event; other event
keypress Sync Yes Element KeyboardEvent Yes Varies: textInput event; launch text composition system; blur and focus events; DOMActivate event; other event
keyup Sync Yes Element KeyboardEvent Yes none
load Async No defaultView, Document, Element Event No none
mousedown Sync Yes Element MouseEvent Yes none
mouseenter Sync No Element MouseEvent No none
mouseleave Sync No Element MouseEvent No none
mousemove Sync Yes Element MouseEvent Yes none
mouseout Sync Yes Element MouseEvent Yes none
mouseover Sync Yes Element MouseEvent Yes none
mouseup Sync Yes Element MouseEvent Yes none
resize Sync No defaultView, Document UIEvent No none
scroll Async No / Yes defaultView, Document, Element UIEvent No none
select Sync Yes Element Event No none
textInput Sync Yes Element TextEvent Yes none
unload Sync No defaultView, Document, Element Event No none
wheel Async Yes defaultView, Document, Element WheelEvent Yes Scroll (or zoom) the document

As an example of interpreting of this table, the event load must trigger event listeners attached on Element nodes for that event and on the capture and target phases. This event cannot be cancelled. If an event listener for the load event is attached to a node other than defaultView, Document, or Element nodes, or if it is attached to the bubbling phase only, this event listener must not be triggered.

The event objects associated with the event types described above may contain context information. Refer to the description of the DOM interfaces for further information.

5.2 Event Module Definitions

The DOM Event Model allows a DOM implementation to support multiple modules of events. The model has been designed to allow addition of new event modules if required. This document does not attempt to define all possible events. For purposes of interoperability, the DOM defines a module of user interface events including lower level device dependent events and a module of document mutation events.

5.2.1 User Interface Event Types

This module defines the feature UIEvents 3.0 and depends on the features Events 3.0 and Views 2.0.

The User Interface event module contains basic event types associated with user interfaces and document manipulation.

Interface UIEvent (introduced in DOM Level 2)

The UIEvent interface provides specific contextual information associated with User Interface events.

To create an instance of the UIEvent interface, use the DocumentEvent.createEvent("UIEvent") method call.


IDL Definition

// Introduced in DOM Level 2:
interface UIEvent : Event {
  readonly attribute views::AbstractView view;
  readonly attribute long            detail;
  void                               initUIEvent(in DOMString typeArg, 
                                                 in boolean canBubbleArg, 
                                                 in boolean cancelableArg, 
                                                 in views::AbstractView viewArg, 
                                                 in long detailArg);
};
                
Attributes
detail of type long, readonly

Specifies some detail information about the Event, depending on the type of event.

view of type views::AbstractView, readonly

The view attribute identifies the AbstractView from which the event was generated.

Methods
initUIEvent

Initializes attributes of an UIEvent object. This method has the same behavior as Event.initEvent().

Parameters
typeArg of type DOMString

Refer to the Event.initEvent() method for a description of this parameter.

canBubbleArg of type boolean

Refer to the Event.initEvent() method for a description of this parameter.

cancelableArg of type boolean

Refer to the Event.initEvent() method for a description of this parameter.

viewArg of type views::AbstractView

Specifies UIEvent.view. This value may be null.

detailArg of type long

Specifies UIEvent.detail.

No Return Value
No Exceptions

The User Interface event types are listed below. Some of these events use the UIEvent interface if generated from a user interface, but the Event interface otherwise, as detailed in each event.

DOMActivate
TypeDOMActivate
InterfaceUIEvent
Sync / AsyncSync
BubblesYes
TargetElement
CancelableYes
Default actionnone
Context info

A user agent must dispatch this event when a button, link, or other state-changing element is activated. Refer to Activation triggers and behavior for more details.

Warning! The DOMActivate event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type in favor of the related event type click. Other specifications may define and maintain their own DOMActivate event type for backwards compatibility.

Note: While DOMActivate and click are not completely equivalent, implemented behavior for the click event type has developed to encompass the most critical accessibility aspects for which the DOMActivate event type was designed, and is more widely implemented. Content authors are encouraged to use the click event type rather than the related mousedown or mouseup event type to ensure maximum accessibility.

The activate event occurs when an element is activated, for instance, thru a mouse click or a keypress. A numerical argument is provided to give an indication of the type of activation that occurs: 1 for a simple activation (e.g. a simple click or Enter), 2 for hyperactivation (for instance a double click or Shift Enter).
load
Typeload
InterfaceUIEvent if generated from a user interface, Event otherwise.
Sync / AsyncAsync
BubblesNo
TargetdefaultView, Document, Element
CancelableNo
Default actionnone
Context info

A user agent must dispatch this event when the DOM implementation finishes loading the resource (such as the document) and any dependent resources (such as images, style sheets, or scripts). Dependent resources that fail to load must not prevent this event from firing if the resource that loaded them is still accessible via the DOM. If this event type is dispatched, implementations are required to dispatch this event at least on the Document node.

unload
Typeunload
InterfaceUIEvent if generated from a user interface, Event otherwise.
Sync / AsyncSync
BubblesNo
TargetdefaultView, Document, Element
CancelableNo
Default actionnone
Context info

A user agent must dispatch this event when the DOM Implementation removes from the environment the resource (such as the document) or any dependent resources (such as images, style sheets, scripts). The document shall be unloaded after the dispatch of this event type. If this event type is dispatched, implementations are required to dispatch this event at least on the Document node.

abort
Typeabort
InterfaceUIEvent if generated from a user interface, Event otherwise.
Sync / AsyncSync
BubblesNo
TargetElement
CancelableNo
Default actionnone
Context info

A user agent must dispatch this event when the loading of a resource has been aborted, such as by a user canceling the load while it is still in progress.

error
Typeerror
InterfaceUIEvent if generated from a user interface, Event otherwise.
Sync / AsyncAsync
BubblesNo
TargetElement
CancelableNo
Default actionnone
Context info

A user agent must dispatch this event when a resource failed to load, or has been loaded but cannot be interpreted according to its semantics, such as an invalid image, a script execution error, or non-well-formed XML.

select
Typeselect
InterfaceUIEvent if generated from a user interface, Event otherwise.
Sync / AsyncSync
BubblesYes
TargetElement
CancelableNo
Default actionnone
Context info

A user agent must dispatch this event when a user selects some text. This event is dispatched after the selection has occurred.

This specification does not provide contextual information to access the selected text. Where applicable, a host language should define rules for how a user may select content (with consideration for international language conventions), at what point the select event is dispatched, and how a content author may access the user-selected content.

Note: In order to access to user-selected content, content authors should use native capabilities of the host languages, such as the Document.getSelection() method of HTML's text selection APIs [HTML5].

Note: The select event may not be available for all elements in all languages. For example, in [HTML5], select events may only be dispatched on only form input and textarea elements. Implementations may dispatch select events in any context deemed appropriate, including text selections outside of form controls, or image or markup selections such as in SVG.

resize
Typeresize
InterfaceUIEvent
Sync / AsyncSync
BubblesNo
TargetdefaultView, Document
CancelableNo
Default actionnone
Context info

A user agent must dispatch this event when a document view has been resized. This event type is dispatched after all effects for that occurrence of resizing of that particular event target have been executed by the user agent.

In the case of a user-initiated resizing, i.e when a user expands or shrinks a browser window by dragging the edge of the frame, the frame undergoes several consecutive size changes, but these intermediate stages must not be dispatched as resize events.

Note: Some user agents may have an optional mode in which the document is reflowed dynamically while the window is resized; in this mode, resize events may be dispatched continuously while the resizing operation is in progress.

Once the user has finished resizing, in a system- and implementation-determined manner such as the release of the pointer button or after a sufficiently long pause, or once any instant resizing (e.g. from a window maximize button or a script effect) has been executed, the user agent must perform any relevant layout recalculations or other actions caused by the resizing, and must subsequently dispatch a single resize event that reflects the final state of the event target. In the case where multiple resize events have been triggered as the result of the same action, even for different event target, the user agent must dispatch each resize event only after the previous resize event has completed its propagation path or been canceled.

Issue: There is no current interoperability here. See ISSUE-113.

A user agent should dispatch the resize event before the document is re-rendered, to provide the content author an opportunity to adjust the content to suit the new size.

Issue: Firing the event between reflow and repaint may be difficult in some UAs (see Mozilla Bug #227495), but it seems the behavior most content authors would want. Should we keep this, or change it to fire after repaint?

The defaultView object should always be resizable. A host language may define certain elements to be resizable, and under what conditions (e.g. specific elements like iframe, or elements with particular characteristics like width and height); however, this specification does not define the behavior for elements.

Note: In some implementations, certain elements may be resizable, such as the object or iframe elements.

Note: The resize event is distinct from the SVG zoom event types, though both may occur at the same time, or as the consequence of the same user action. In particular, browser “font zooming” or “page zooming” should not necessarily trigger a resize event.

Note: In previous DOM Events specifications, the resize event type was defined to have a bubbling phase, but for performance reasons, this was not implemented in most user agents, and this specification removes the bubbling phase for this event.

scroll
Typescroll
InterfaceUIEvent
Sync / AsyncAsync
BubblesNo / Yes
TargetdefaultView, Document, Element
CancelableNo
Default actionnone
Context info

A user agent must dispatch this event when a document view or an element has been scrolled. This event type is dispatched after the scroll has occurred.

Note: When dispatched on the Document element, this event type must bubble to the defaultView object.

5.2.2 Focus Event Types

This module defines the feature FocusEvents 3.0 and depends on the feature UIEvents 3.0.

Note: This interface and its associated event types and focus event order were designed in accordance to the concepts and guidelines defined in User Agent Accessibility Guidelines 2.0 [UAAG 2.0], with particular attention on the focus mechanism and the terms defined in the glossary entry for focus.

Interface FocusEvent (introduced in DOM Level 2)

The FocusEvent interface provides specific contextual information associated with Focus events.

To create an instance of the FocusEvent interface, use the DocumentEvent.createEvent("FocusEvent") method call.


IDL Definition

// Introduced in DOM Level 3:
interface FocusEvent : UIEvent {
  readonly attribute EventTarget   relatedTarget;
  void                             initFocusEvent(in DOMString typeArg, 
                                                  in boolean canBubbleArg, 
                                                  in boolean cancelableArg, 
                                                  in views::AbstractView viewArg, 
                                                  in long detailArg, 
                                                  in EventTarget relatedTargetArg);
};
              
Attributes
relatedTarget of type EventTarget, readonly

Used to identify a secondary EventTarget related to a Focus event, depending on the type of event.

For security reasons with nested browsing contexts, when tabbing into or out of a nested context, the relevant EventTarget should be null.

Issue: Alternate approach:
For security reasons with nested browsing contexts, when tabbing into or out of a nested context, the relevant EventTarget should be the element containing browsing context (e.g. the iframe), even if that element cannot normally receive focus.
See [Comments from Olli Pettay]

Methods
initFocusEvent
Initializes attributes of a FocusEvent object. This method has the same behavior as UIEvent.initUIEvent().
Parameters
typeArg of type DOMString

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

canBubbleArg of type boolean

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

cancelableArg of type boolean

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

viewArg of type views::AbstractView

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

detailArg of type long

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

relatedTargetArg of type EventTarget

Specifies FocusEvent.relatedTarget. This value may be null.

No Return Value
No Exceptions

The Focus event types are listed below.

5.2.2.1 Focus Event Order

The focus events defined in this specification occur in a set order relative to one another. The following is the typical sequence of events when a focus is shifted between elements (this order assumes that no element is initially focused):

  1. [user shifts focus] focusin (before first target element receives focus)
  2. focus (after first target element receives focus)
  3. DOMFocusIn (if supported)
  4. [user shifts focus] focusout (before first target element loses focus)
  5. focusin (before second target element receives focus)
  6. blur (after first target element loses focus)
  7. DOMFocusOut (if supported)
  8. focus (after second target element receives focus)
  9. DOMFocusIn (if supported)

Issue: Behavior of focus events when interacting with focus()/blur() methods needs to be defined. See [ISSUE-102]

5.2.2.2 Document Focus and Focus Context

This event module includes event types for notification of changes in document focus. Depending on the environment, document focus may be distinct from user agent focus and operating system focus; this is referred to as focus context. For example, in a typical desktop browser environment, the operating system context focus may be on one of many different applications, one of which is the browser; when the browser has focus, the user may shift the application context focus (such as with the tab key) among different browser user interface fields (e.g. the Web site location bar, a search field, etc.) before or after achieving document focus; once the document itself has focus, sequential shifting of focus will step through the focusable elements in the document. The event types defined in this specification deal exclusively with document focus, and the event target identified in the event details must only be part of the document or documents in the window, never a part of the browser or operating system, even when switching from one focus context to another.

Normally, a document always has a focused element, even if it is the document element itself, and a persistent focus ring; when switching between focus contexts, the document's currently focused element and focus ring normally remain the their current state; for example, if a document has three focusable elements, with the second element focused, when a user changes operating system focus to another application and then back to the browser, the second element will still be focused within the document, and tabbing will change the focus to the third element. A host language may define specific elements which may or may not receive focus, the conditions user which an element may receive focus, the means by which focus may be changed, and the order in which the focus changes. For example, in some cases an element may be given focus by moving a pointer over it, while other circumstances may require a mouse click; some elements may not be focusable at all, and some may be focusable only by special means (clicking on the element), but not by tabbing to it. Documents may contain multiple focus rings. Other specifications may define a more complex focus model than is described in this specification, including allowing multiple elements to have the current focus.

blur
Typeblur
InterfaceFocusEvent
Sync / AsyncSync
BubblesNo
TargetElement
CancelableNo
Default actionnone
Context info

A user agent must dispatch this event when an event target loses focus. The focus shall be taken from the element before the dispatch of this event type. This event type is similar to focusout, but is dispatched after focus is shifted, and does not bubble.

DOMFocusIn
TypeDOMFocusIn
InterfaceFocusEvent
Sync / AsyncSync
BubblesYes
TargetElement
CancelableNo
Default actionnone
Context info

A user agent must dispatch this event when an event target receives focus. The focus shall be given to the element before the dispatch of this event type. This event type shall be dispatched after the event type focus.

Warning! the DOMFocusIn event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type in favor of the related event types focus and focusin.

DOMFocusOut
TypeDOMFocusOut
InterfaceFocusEvent
Sync / AsyncSync
BubblesYes
TargetElement
CancelableNo
Default actionnone
Context info

A user agent must dispatch this event when an event target loses focus. The focus shall be taken from the element before the dispatch of this event type. This event type shall be dispatched after the event type blur.

Warning! the DOMFocusOut event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type in favor of the related event types blur and focusout.

focus
Typefocus
InterfaceFocusEvent
Sync / AsyncSync
BubblesNo
TargetElement
CancelableNo
Default actionnone
Context info

A user agent must dispatch this event when an event target receives focus. The focus shall be given to the element before the dispatch of this event type. This event type is similar to focusin, but is dispatched after focus is shifted, and does not bubble.

focusin
Typefocusin
InterfaceFocusEvent
Sync / AsyncSync
BubblesYes
TargetElement
CancelableNo
Default actionnone
Context info

A user agent must dispatch this event when an event target is about to receive focus. This event type must be dispatched before the element is given focus. The event target must be the element which is about to receive focus. This event type is similar to focus, but is dispatched before focus is shifted, and does bubble.

Note: When using this event type, the content author may use the event's FocusEvent.relatedTarget attribute (or a host-language-specific method or means) to get the currently focused element before the focus shifts to the next focus event target, thus having optional access to both the element losing focus and the element gaining focus without the use of the blur or focusout event types.

focusout
Typefocusout
InterfaceFocusEvent
Sync / AsyncSync
BubblesYes
TargetElement
CancelableNo
Default actionnone
Context info

A user agent must dispatch this event when an event target is about to lose focus. This event type must be dispatched before the element loses focus. The event target must be the element which is about to lose focus. This event type is similar to blur, but is dispatched before focus is shifted, and does bubble.

5.2.3 Mouse Event Types

This module defines the feature MouseEvents 3.0 and depends on the feature UIEvents 3.0.

The Mouse event module originates from the [HTML 4.01] onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, and onmouseout attributes. This event module is specifically designed for use with pointing input devices, such as a mouse or a trackball.

Interface MouseEvent (introduced in DOM Level 2)

The MouseEvent interface provides specific contextual information associated with Mouse events.

In the case of nested elements mouse events are always targeted at the most deeply nested element. Ancestors of the targeted element may use bubbling to obtain notification of mouse events which occur within their descendent elements.

To create an instance of the MouseEvent interface, use the DocumentEvent.createEvent("MouseEvent") method call.

Note: When initializing MouseEvent objects using initMouseEvent or initMouseEventNS, implementations should use the client coordinates clientX and clientY for calculation of other coordinates (such as target coordinates exposed by DOM Level 0 implementations or other proprietary attributes, e.g. pageX).


IDL Definition

// Modified in DOM Level 3:
interface MouseEvent : UIEvent {
  readonly attribute long            screenX;
  readonly attribute long            screenY;
  readonly attribute long            clientX;
  readonly attribute long            clientY;
  readonly attribute boolean         ctrlKey;
  readonly attribute boolean         shiftKey;
  readonly attribute boolean         altKey;
  readonly attribute boolean         metaKey;
  readonly attribute unsigned short  button;  
  readonly attribute unsigned short  buttons;
  readonly attribute                 EventTarget     relatedTarget;
  void                               initMouseEvent(in DOMString typeArg, 
                                                in boolean canBubbleArg, 
                                                in boolean cancelableArg, 
                                                in views::AbstractView viewArg, 
                                                in long detailArg, 
                                                in long screenXArg, 
                                                in long screenYArg, 
                                                in long clientXArg, 
                                                in long clientYArg, 
                                                in boolean ctrlKeyArg, 
                                                in boolean altKeyArg, 
                                                in boolean shiftKeyArg, 
                                                in boolean metaKeyArg, 
                                                in unsigned short buttonArg, 
                                                in EventTarget relatedTargetArg);
  // Introduced in DOM Level 3:
  boolean                            getModifierState(in DOMString keyArg);
};
              
Attributes
altKey of type boolean, readonly

Refer to the KeyboardEvent.altKey attribute.

button of type unsigned short, readonly
During mouse events caused by the depression or release of a mouse button, button shall be used to indicate which pointer device button changed state.

The value of the MouseEvent.button attribute must be as follows:

  • 0 must indicate the primary button of the device (in general, the left button or the only button on single-button devices, used to activate a user interface control or select text).
  • 1 must indicate the auxiliary button (in general, the middle button, often combined with a mouse wheel).
  • 2 must indicate the secondary button (in general, the right button, often used to display a context menu).

Some pointing devices may provide or simulate more buttons, and values higher than 2 may be used to represent such buttons.

buttons of type unsigned short, readonly
During mouse events caused by the depression or release of a mouse button, buttons shall be used to indicate which combination of mouse buttons are currently being pressed, expressed as a bitmask. Note: This should not be confused with the button attribute.

The value of the MouseEvent.buttons attribute must be as follows:

  • 0 must indicates no button is currently active.
  • 1 must indicate the primary button of the device (in general, the left button or the only button on single-button devices, used to activate a user interface control or select text).
  • 2 must indicate the secondary button (in general, the right button, often used to display a context menu), if present.
  • 4 must indicate the auxiliary button (in general, the middle button, often combined with a mouse wheel).

Some pointing devices may provide or simulate more buttons. To represent such buttons, the value must be doubled for each successive button (in the binary series 8, 16, 32, ... ), and the buttons should alternate sides of the device, from left to right. For example, with a 5-button mouse, the primary button (on the left) would have the value 1, the secondary button (on the right) would have the value 2, the auxiliary button (in the middle) would have the value 4, the fourth button (on the left) would have the value 8, and the fifth button (on the right) would have the value 16.

Note: Because the sum of any set of button values is a unique number, a content author can use a bitwise operation to determine how many buttons are currently being pressed and which buttons they are, for an arbitrary number of mouse buttons on a device, e.g. the value 3 indicates that the left and right button are currently both pressed, while the value 5 indicates that the left and middle button are currently both pressed.

clientX of type long, readonly

The horizontal coordinate at which the event occurred relative to the viewport associated with the event.

clientY of type long, readonly

The vertical coordinate at which the event occurred relative to the viewport associated with the event.

ctrlKey of type boolean, readonly

Refer to the KeyboardEvent.ctrlKey attribute.

metaKey of type boolean, readonly

Refer to the KeyboardEvent.metaKey attribute.

relatedTarget of type EventTarget, readonly

Used to identify a secondary EventTarget related to a UI event, depending on the type of event.

screenX of type long, readonly

The horizontal coordinate at which the event occurred relative to the origin of the screen coordinate system.

screenY of type long, readonly

The vertical coordinate at which the event occurred relative to the origin of the screen coordinate system.

shiftKey of type boolean, readonly

Refer to the KeyboardEvent.shiftKey attribute.

Methods
getModifierState introduced in DOM Level 3
Queries the state of a modifier using a key value. See also Modifier keys.
Parameters
keyArg of type DOMString

Refer to the KeyboardEvent.getModifierState() method for a description of this parameter.

Return Value

boolean

true if it is a modifier key and the modifier is activated, false otherwise.

No Exceptions
initMouseEvent

Initializes attributes of a MouseEvent object. This method has the same behavior as UIEvent.initUIEvent().

Parameters
typeArg of type DOMString

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

canBubbleArg of type boolean

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

cancelableArg of type boolean

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

viewArg of type views::AbstractView

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

detailArg of type long

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

screenXArg of type long

Specifies MouseEvent.screenX.

screenYArg of type long

Specifies MouseEvent.screenY.

clientXArg of type long

Specifies MouseEvent.clientX.

clientYArg of type long

Specifies MouseEvent.clientY.

ctrlKeyArg of type boolean

Specifies MouseEvent.ctrlKey.

altKeyArg of type boolean

Specifies MouseEvent.altKey.

shiftKeyArg of type boolean

Specifies MouseEvent.shiftKey.

metaKeyArg of type boolean

Specifies MouseEvent.metaKey.

buttonArg of type unsigned short

Specifies MouseEvent.button.

relatedTargetArg of type EventTarget

Specifies MouseEvent.relatedTarget. This value may be null.

No Return Value
No Exceptions

The Mouse event types are listed below. In the case of nested elements, mouse event types are always targeted at the most deeply nested element. Ancestors of the targeted element may use bubbling to obtain notification of mouse events which occur within its descendent elements.

Implementations must maintain the current click count when generating mouse events. This shall be a non-negative integer indicating the number of consecutive clicks of a pointing device button during a user action. The notion of consecutive clicks depends on the environment configuration. For example, a dblclick event type might not happen if there is a long delay between the two clicks. Note: The value of UIEvent.detail for a number of clicks greater than 2 is platform-dependent. For example, on the Windows OS, the click-count series seems to be 1, 2, 3, 2, 3, while on MacOS, the click-count series seems to be 1, 2, 3, 4, 5, ....

5.2.3.2 Mouse Event Order

Certain mouse events defined in this specification occur in a set order relative to one another. The following is the typical sequence of events when a pointing device's cursor is moved over an element:

  1. mousemove
  2. mouseover
  3. mouseenter
  4. mousemove (multiple events)
  5. mouseout
  6. mouseleave

The following is the typical sequence of events when a button associated with a pointing device (e.g., a mouse button or trackpad) is pressed and released over an element:

  1. mousedown
  2. mousemove (optional, multiple events, some limits)
  3. mouseup
  4. click
  5. mousemove (optional, multiple events, some limits)
  6. mousedown
  7. mousemove (optional, multiple events, some limits)
  8. mouseup
  9. click
  10. dblclick

Note that the lag time, degree, distance, and number of mousemove events allowed between the mousedown and mouseup events while still firing a click or dblclick event shall be implementation-, device-, and platform-specific. Each implementation should determine the appropriate hysteresis tolerance, but in general should fire click and dblclick events when the event target of the associated mousedown and mouseup events is the same element with no mouseout or mouseleave events intervening, and should not fire click and dblclick events when the event target of the associated mousedown and mouseup events is different.

click
Typeclick
InterfaceMouseEvent
Sync / AsyncSync
BubblesYes
TargetElement
CancelableYes
Default actionVaries
Context info

The click event type must be dispatched on the topmost event target indicated by the pointer, when the user presses down and releases the pointer button, or otherwise activates the pointer in a manner that simulates such an action. The actuation method of the mouse button must depend upon the pointer device and the environment configuration, e.g. it may depend on the screen location or the delay between the press and release of the pointing device button.

The click event may be preceded by the mousedown and mouseup events on the same element, disregarding changes between other node types (e.g. text nodes). Depending upon the environment configuration, the click event may be dispatched if one or more of the event types mouseover, mousemove, and mouseout occur between the press and release of the pointing device button. The click event may also be followed by the dblclick event.

Example: If a user mouses down on a text node child of a <p> element which has been styled with a large line-height, shifts the mouse slightly such that it is no longer over an area containing text but is still within the containing block of that <p> element (i.e. the pointer is between lines of the same text block, but not over the text node per se), then subsequently mouses up, this should still trigger a click event (if it falls within the normal temporal hysteresis for a click), since the user has stayed within the scope of the same element; user-agent-generated mouse events are not dispatched on text nodes.

In addition to being associated with pointer devices, the click event type must be dispatched as part of an element activation, as described in Activation triggers and behavior.

Note: For maximum accessibility, content authors should use the click event type when defining activation behavior for custom controls, rather than other pointing-device event types such as mousedown or mouseup, which are more device-specific. Though the click event type has its origins in pointer devices (e.g. a mouse), subsequent implementation enhancements have extended it beyond that association, and it should be considered a device-independent event type for element activation.

The default action of the click event type varies based on the proximal event target of the event and the value of the MouseEvent.button or MouseEvent.buttons attributes. Typical default actions of the click event type are as follows:

dblclick
Typedblclick
InterfaceMouseEvent
Sync / AsyncSync
BubblesYes
TargetElement
CancelableYes
Default actionnone
Context info

A user agent must dispatch this event when a pointing device button is clicked twice over an element. The definition of a double click depends on the environment configuration, except that the event target must be the same between mousedown, mouseup, and dblclick. This event type must be dispatched after the event type click if a click and double click occur simultaneously, and after the event type mouseup otherwise.

Note: Canceling the click event must not not affect the firing of a dblclick event.

As with the click event type, the default action of the dblclick event type varies based on the proximal event target of the event and the value of the MouseEvent.button or MouseEvent.buttons attributes. Normally, the typical default actions of the dblclick event type match those of the click event type, with the following additional behavior:

mousedown
Typemousedown
InterfaceMouseEvent
Sync / AsyncSync
BubblesYes
TargetElement
CancelableYes
Default actionnone
Context info

A user agent must dispatch this event when a pointing device button is pressed over an element.

mouseenter
Typemouseenter
InterfaceMouseEvent
Sync / AsyncSync
BubblesNo
TargetElement
CancelableNo
Default actionnone
Context info

A user agent must dispatch this event when a pointing device is moved onto the boundaries of an element or one of its descendent elements. This event type is similar to mouseover, but differs in that it does not bubble, and must not be dispatched when the pointer device moves from an element onto the boundaries of one of its descendent elements.

Note: There are similarities between this event type and the CSS :hover pseudo-class [CSS2]. See also the mouseleave event type.

mouseleave
Typemouseleave
InterfaceMouseEvent
Sync / AsyncSync
BubblesNo
TargetElement
CancelableNo
Default actionnone
Context info

A user agent must dispatch this event when a pointing device is moved off of the boundaries of an element and all of its descendent elements. This event type is similar to mouseout, but differs in that does not bubble, and that it must not be dispatched until the pointing device has left the boundaries of the element and the boundaries of all of its children.

Note: There are similarities between this event type and the CSS :hover pseudo-class [CSS2]. See also the mouseenter event type.

mousemove
Typemousemove
InterfaceMouseEvent
Sync / AsyncSync
BubblesYes
TargetElement
CancelableYes
Default actionnone
Context info

A user agent must dispatch this event when a pointing device is moved while it is over an element. The frequency rate of events while the pointing device is moved shall be implementation-, device-, and platform-specific, but multiple consecutive mousemove events should be fired for sustained pointer-device movement, rather than a single event for each instance of mouse movement. Implementations are encouraged to determine the optimal frequency rate to balance responsiveness with performance.

mouseout
Typemouseout
InterfaceMouseEvent
Sync / AsyncSync
BubblesYes
TargetElement
CancelableYes
Default actionnone
Context info

A user agent must dispatch this event when a pointing device is moved off of the boundaries of an element. This event type is similar to mouseleave, but differs in that does bubble, and that it must be dispatched when the pointer device moves from an element onto the boundaries of one of its descendent elements.

Note: See also the mouseover event type.

mouseover
Typemouseover
InterfaceMouseEvent
Sync / AsyncSync
BubblesYes
TargetElement
CancelableYes
Default actionnone
Context info

A user agent must dispatch this event when a pointing device is moved onto the boundaries of an element. This event type is similar to mouseenter, but differs in that does bubble, and that it must be dispatched when the pointer device moves onto the boundaries of an element whose ancestor element is the event target for the same event listener instance.

Note: See also the mouseout event type.

mouseup
Typemouseup
InterfaceMouseEvent
Sync / AsyncSync
BubblesYes
TargetElement
CancelableYes
Default actionnone
Context info

A user agent must dispatch this event when a pointing device button is released over an element.

5.2.4 Wheel Event Types

This module defines the feature WheelEvents 3.0 and depends on the feature MouseEvents 3.0.

Wheels are devices that can be rotated in one or more spatial dimensions, and which may or may not be associated with a pointer device. The coordinate system depends on the environment configuration. As an example, the environment may be configured to associate vertical scrolling with rotation along the y-axis, horizontal scrolling with rotation along the x-axis, and zooming with rotation along the z-axis. The deltax, deltaY, and deltaX attributes of WheelEvent objects indicate the distance of the rotation, as specified in the delta definition.

Interface WheelEvent (introduced in DOM Level 3)

The WheelEvent interface provides specific contextual information associated with omnidirectional mouse wheel events.

To create an instance of the WheelEvent interface, use the DocumentEvent.createEvent("WheelEvent") method call.


IDL Definition

// Introduced in DOM Level 3:
interface WheelEvent : MouseEvent {

  // DeltaModeCode
  const unsigned long                DOM_DELTA_PIXEL       = 0x00;
  const unsigned long                DOM_DELTA_LINE        = 0x01;
  const unsigned long                DOM_DELTA_PAGE        = 0x02;

  readonly attribute long            deltaX;
  readonly attribute long            deltaY;
  readonly attribute long            deltaZ;
  readonly attribute unsigned long   deltaMode;    
  void                               initWheelEvent(in DOMString typeArg, 
                                                    in boolean canBubbleArg, 
                                                    in boolean cancelableArg, 
                                                    in views::AbstractView viewArg, 
                                                    in long detailArg, 
                                                    in long screenXArg, 
                                                    in long screenYArg, 
                                                    in long clientXArg, 
                                                    in long clientYArg, 
                                                    in unsigned short buttonArg, 
                                                    in EventTarget relatedTargetArg, 
                                                    in DOMString modifiersListArg, 
                                                    in long deltaXArg, 
                                                    in long deltaYArg, 
                                                    in long deltaZArg, 
                                                    in unsigned long deltaMode);
};
              
Definition group DeltaModeCode

This set of constants shall be used to indicate the units of measurement for the delta values. The precise measurement is specific to device, operating system, and application configurations.

Defined Constants
DOM_DELTA_PIXEL
The units of measurement for the delta shall be pixels. This is the most typical case in most operating system and implementation configurations.
DOM_DELTA_LINE
The units of measurement for the delta shall be individual lines of text. This is the case for many form controls.
DOM_DELTA_PAGE
The units of measurement for the delta shall be pages, either defined as a single screen or as a demarcated page.
Attributes
deltaX of type long, readonly

The distance the wheel has rotated around the x-axis.

deltaY of type long, readonly

The distance the wheel has rotated around the y-axis.

deltaZ of type long, readonly

The distance the wheel has rotated around the z-axis.

deltaMode of type unsigned long, readonly
The deltaMode attribute contains an indication of to indicate the units of measurement for the delta values. The default value is DOM_DELTA_PIXEL (pixels). The value of deltaMode may be different for each of deltaX, deltaY, and deltaZ, based on system configuration.
Methods
initWheelEvent introduced in DOM Level 3

Initializes attributes of a WheelEvent object. This method has the same behavior as MouseEvent.initMouseEvent().

Parameters
typeArg of type DOMString

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

canBubbleArg of type boolean

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

cancelableArg of type boolean

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

viewArg of type views::AbstractView

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

detailArg of type long

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

screenXArg of type long

Refer to the MouseEvent.initMouseEvent() method for a description of this parameter.

screenYArg of type long

Refer to the MouseEvent.initMouseEvent() method for a description of this parameter.

clientXArg of type long

Refer to the MouseEvent.initMouseEvent() method for a description of this parameter.

clientYArg of type long

Refer to the MouseEvent.initMouseEvent() method for a description of this parameter.

buttonArg of type unsigned short

Refer to the MouseEvent.initMouseEvent() method for a description of this parameter.

relatedTargetArg of type EventTarget

Refer to the MouseEvent.initMouseEvent() method for a description of this parameter.

modifiersListArg of type DOMString

Refer to the MouseEvent.initMouseEvent() method for a description of this parameter.

deltaXArg of type long

Specifies WheelEvent.deltaX.

deltaYArg of type long

Specifies WheelEvent.deltaY.

deltaZArg of type long

Specifies WheelEvent.deltaZ.

deltaModeArg of type unsigned long

Specifies WheelEvent.deltaMode.

No Return Value
No Exceptions
wheel
Typewheel
InterfaceWheelEvent
Sync / AsyncAsync
BubblesYes
TargetdefaultView, Document, Element
CancelableYes
Default actionscroll (or zoom) the document
Context info

A user agent must dispatch this event when a mouse wheel has been rotated around any axis, or when an equivalent input device (such as a mouse-ball, certain tablets or touchpads, etc.) has emulated such an action.

The typical default action of the wheel event type is to scroll (or in some cases, zoom) the document by the indicated amount. If this event is canceled, the implementation must not scroll or zoom the document (or perform whatever other implementation-specific default action is associated with this event type).

Due to a lack of early standardization for a mouse-wheel event type, there are several related proprietary events which have been implemented by different user agents, with different names and characteristics. This specification does not attempt to specify these legacy events due to lack of interoperability, but supplies the following equivalency information which may help implementers and content authors. A user agent may dispatch an event of one or more of the following event types as a default action of a wheel event, depending upon the property values of the wheel event and implementation support:

mousewheel

Dispatched when WheelEvent.deltaY is non-zero.

In Microsoft Internet Explorer:

mousewheel.wheelDelta = -(WheelEvent.deltaY) / 120

In Opera:

mousewheel.wheelDelta = WheelEvent.deltaY / 120

DOMMouseScroll

Dispatched when WheelEvent.deltaY is non-zero.

In Mozilla Firefox:

DOMMouseScroll.detail = WheelEvent.deltaY / 3

DOMMouseScroll.axis = VERTICAL_AXIS

Dispatched when WheelEvent.deltaX is non-zero.

In Mozilla Firefox:

DOMMouseScroll.detail = WheelEvent.deltaX / 3

DOMMouseScroll.axis = HORIZONTAL_AXIS

MozMousePixelScroll

Dispatched when WheelEvent.deltaY is non-zero, and deltaMode is DOM_DELTA_PIXEL.

In Mozilla Firefox:

MozMousePixelScroll.detail = WheelEvent.deltaY / 3

MozMousePixelScroll.axis = VERTICAL_AXIS

Dispatched when WheelEvent.deltaX is non-zero, and deltaMode is DOM_DELTA_PIXEL.

In Mozilla Firefox:

MozMousePixelScroll.detail = WheelEvent.deltaX / 3

MozMousePixelScroll.axis = HORIZONTAL_AXIS

Note: In some user agents, or with some input devices, the speed that the wheel has been turned may affect the delta values, with a faster speed producing a higher delta value.

Note: Though events of event type wheel often result in scrolling, which results in a scroll event, there is no direct connection between these event types, and the scroll event is not a default action of the wheel event.

5.2.5 Text Event Types

This module defines the feature TextEvents 3.0 and depends on the feature UIEvents 3.0.

The text event module originates from the [HTML 4.01] onkeypress attribute. Unlike this attribute, the event type textInput applies only to characters and is designed for use with any text input devices, not just keyboards. Refer to Keyboard events and key values for examples on how text events are used in combination with keyboard events.

Interface TextEvent (introduced in DOM Level 3)

The TextEvent interface provides specific contextual information associated with Text Events.

To create an instance of the TextEvent interface, use the DocumentEvent.createEvent("TextEvent") method call.


IDL Definition

// Introduced in DOM Level 3:
interface TextEvent : UIEvent {

  // InputMethodCode
  const unsigned long                DOM_INPUT_METHOD_UNKNOWN       = 0x00;
  const unsigned long                DOM_INPUT_METHOD_KEYBOARD      = 0x01;
  const unsigned long                DOM_INPUT_METHOD_PASTE         = 0x02;
  const unsigned long                DOM_INPUT_METHOD_DROP          = 0x03;
  const unsigned long                DOM_INPUT_METHOD_IME           = 0x04;
  const unsigned long                DOM_INPUT_METHOD_OPTION        = 0x05;
  const unsigned long                DOM_INPUT_METHOD_HANDWRITING   = 0x06;
  const unsigned long                DOM_INPUT_METHOD_VOICE         = 0x07;
  const unsigned long                DOM_INPUT_METHOD_MULTIMODAL    = 0x08;
  const unsigned long                DOM_INPUT_METHOD_SCRIPT        = 0x09;

  readonly attribute DOMString       data;
  readonly attribute unsigned long   inputMethod;  
  void                               initTextEvent(in DOMString typeArg, 
                                                   in boolean canBubbleArg, 
                                                   in boolean cancelableArg, 
                                                   in views::AbstractView viewArg, 
                                                   in DOMString dataArg, 
                                                   in unsigned long inputMethod);
};
                
Definition group InputMethodCode

This set of constants shall be used to indicate the origin of the text input. In case a DOM implementation wishes to provide a new location information, a value different from the following constant values must be used.

Defined Constants
DOM_INPUT_METHOD_UNKNOWN
The text string was input by an unknown means.
DOM_INPUT_METHOD_KEYBOARD
The text string was input through a keyboard. This may be associated with one or more of keypress, keydown, or keyup events.
DOM_INPUT_METHOD_PASTE
The text string was pasted in from a clipboard. This may be associated with a paste event, specified elsewhere.
DOM_INPUT_METHOD_DROP
The text string was inserted as part of a drag-and-drop operation. This may be associated with a drop event, specified elsewhere.
DOM_INPUT_METHOD_IME
The text string was entered through an Input Method Editor. This may be associated with a compositionend event.
DOM_INPUT_METHOD_OPTION
The text string was selected from a set of options presented, such as from a form. This may be associated with various other events, specified elsewhere.
DOM_INPUT_METHOD_HANDWRITING
The text string was input through a pen/tablet device and processed by handwriting recognition software. This may be associated with a specific event defined elsewhere.
DOM_INPUT_METHOD_VOICE
The text string was input by a voice device and interpreted by speech recognition software. This may be associated with a specific event defined elsewhere.
DOM_INPUT_METHOD_MULTIMODAL
The text string was inserted as part of an operation involving multiple input modalities in combination, such as pointer-enhanced speech. This may be associated with various other events, specified elsewhere.
DOM_INPUT_METHOD_SCRIPT
The text string was inserted via a script operation on the DOM. This may be associated with one or more mutation events.
Attributes
data of type DOMString, readonly

data holds the value of the characters generated by the character device. This may be a single Unicode character or a non-empty sequence of Unicode characters [Unicode]. Characters should be normalized as defined by the Unicode normalization form NFC, defined in [UAX #15]. This attribute cannot be null or contain the empty string.

inputMethod of type unsigned long, readonly

The inputMethod attribute contains an indication of the origin of the text input, as described in InputMethodCode.

Methods
initTextEvent

Initializes attributes of a TextEvent object. This method has the same behavior as UIEvent.initUIEvent(). The value of UIEvent.detail remains undefined.

Parameters
typeArg of type DOMString

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

canBubbleArg of type boolean

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

cancelableArg of type boolean

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

viewArg of type views::AbstractView

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

dataArg of type DOMString

Specifies TextEvent.data.

inputMethodArg of type unsigned long

Specifies TextEvent.inputMethod.

No Return Value
No Exceptions

The text event type is listed below.

textInput
TypetextInput
InterfaceTextEvent
Sync / AsyncSync
BubblesYes
TargetElement
CancelableYes
Default actionnone
Context info

A user agent must dispatch this event when one or more characters have been entered. These characters may originate from a variety of sources, e.g., characters resulting from a key being pressed or released on a keyboard device, from the processing of an input method editor, or resulting from a voice command. Where a “paste” operation generates a simple sequence of characters, i.e. a text passage without any structure or style information, this event type should be generated as well.

5.2.6 Keyboard Event Types

This module defines the feature KeyboardEvents 3.0 and depends on the feature UIEvents 3.0.

Keyboard events are device dependent, i.e. they rely on the capabilities of the input devices and how they are mapped in the operating systems. It is therefore highly recommended to rely on Text event types when dealing with character input. Refer to Keyboard events and key values for more details, including examples on how Keyboard Events are used in combination with Composition Events.

Interface KeyboardEvent (introduced in DOM Level 3)

The KeyboardEvent interface provides specific contextual information associated with keyboard devices. Each keyboard event references a key using a value. Keyboard events are commonly directed at the element that has the focus.

The KeyboardEvent interface provides convenient attributes for some common modifiers keys: KeyboardEvent.ctrlKey, KeyboardEvent.shiftKey, KeyboardEvent.altKey, KeyboardEvent.metaKey. These attributes are equivalent to using the method KeyboardEvent.getModifierState(keyArg) with 'Control', 'Shift', 'Alt', or 'Meta' respectively.

To create an instance of the KeyboardEvent interface, use the DocumentEvent.createEvent("KeyboardEvent") method call.


IDL Definition

// Introduced in DOM Level 3:
interface KeyboardEvent : UIEvent {

  // KeyLocationCode
  const unsigned long                DOM_KEY_LOCATION_STANDARD      = 0x00;
  const unsigned long                DOM_KEY_LOCATION_LEFT          = 0x01;
  const unsigned long                DOM_KEY_LOCATION_RIGHT         = 0x02;
  const unsigned long                DOM_KEY_LOCATION_NUMPAD        = 0x03;
  const unsigned long                DOM_KEY_LOCATION_MOBILE        = 0x04;
  const unsigned long                DOM_KEY_LOCATION_JOYSTICK      = 0x05;

  readonly attribute DOMString       char;
  readonly attribute DOMString       key;
  readonly attribute unsigned long   keyCode;
  readonly attribute unsigned long   location;
  readonly attribute boolean         ctrlKey;
  readonly attribute boolean         shiftKey;
  readonly attribute boolean         altKey;
  readonly attribute boolean         metaKey;
  readonly attribute boolean         repeat;
  boolean                            getModifierState(in DOMString keyArg);
  void                               initKeyboardEvent(in DOMString typeArg, 
                                                       in boolean canBubbleArg, 
                                                       in boolean cancelableArg, 
                                                       in views::AbstractView viewArg, 
                                                       in DOMString keyArg, 
                                                       in unsigned long locationArg, 
                                                       in DOMString modifiersListArg,
                                                       in boolean repeat);
};
                
Definition group KeyLocationCode

This set of constants shall be used to indicate the location of a key on the device. In case a DOM implementation wishes to provide a new location information, a value different from the following constant values must be used.

Defined Constants
DOM_KEY_LOCATION_LEFT
The key activated shall be in the left key location (there is more than one possible location for this key). Example: the left 'Control' key on a PC 101 Key US keyboard.
DOM_KEY_LOCATION_NUMPAD
The key activation originated on the numeric keypad or with a virtual key corresponding to the numeric keypad. Example: the '1' key on a PC 101 Key US keyboard located on the numeric pad.
DOM_KEY_LOCATION_RIGHT
The key activation shall be in the right key location (there is more than one possible location for this key). Example: the right 'Shift' key on a PC 101 Key US keyboard.
DOM_KEY_LOCATION_STANDARD
The key activation shall not be distinguished as the left or right version of the key, and did not originate from the numeric keypad (or did not originate with a virtual key corresponding to the numeric keypad). Example: the 'Q' key on a PC 101 Key US keyboard.
DOM_KEY_LOCATION_MOBILE
The key activation originated on a mobile device, either on a physical keypad or a virtual keyboard. Example: the '#' key or softkey on a mobile device.
DOM_KEY_LOCATION_JOYSTICK
The key activation originated on a game controller or a joystick on a mobile device. Example: the 'DownLeft' key on a game controller.
Attributes
altKey of type boolean, readonly
true if the alternative (Alt) key modifier is activated.

Note: The Option key modifier on Macintosh systems must be represented using this key modifier.

ctrlKey of type boolean, readonly

true if the control (Ctrl) key modifier is activated.

char of type DOMString, readonly

char holds the character value of the key pressed. The value must be a Unicode character string, conforming to the algorithm for determining the key value defined in this specification. For a key associated with a macro to insert multiple characters, the value of the char attribute will hold the entire sequence of characters. For a key which does not have a character representation, the value must be null.

Note: the char attribute is not related to the legacy charCode attribute and does not have the same set of values.

key of type DOMString, readonly

key holds the key value of the key pressed. If the value is a character, it must match the value of the KeyboardEvent.char attribute; if the value is a control key which has no printed representation, it must be one of the key values defined in the key values set, as determined by the algorithm for determining the key value. Implementations that are unable to identify a key must use the key value 'Unidentified'.

Note: the key attribute is not related to the legacy KeyboardEvent.keyCode attribute and does not have the same set of values.

keyCode of type unsigned long, readonly

keyCode holds a system- and implementation-dependent numerical code signifying the unmodified identifier associated with the key pressed. Unlike the KeyboardEvent.key or KeyboardEvent.char attributes, the set of possible values are not defined in this specification; typically, these value of the keyCode should represent the decimal codepoint in ASCII [RFC20][US-ASCII] or Windows 1252 [WIN1252], but may be drawn from a different appropriate character set. Implementations that are unable to identify a key must use the key value 0.

location of type unsigned long, readonly

The location attribute contains an indication of the location of the key on the device, as described in Keyboard event types.

metaKey of type boolean, readonly
true if the meta (Meta) key modifier is activated.

Note: The Command key modifier on Macintosh systems must be represented using this key modifier.

shiftKey of type boolean, readonly

true if the shift (Shift) key modifier is activated.

repeat of type boolean, readonly
true if the key has been pressed in a sustained manner. Depending on the system configuration, holding down a key results may result in multiple consecutive keydown events, keypress events, and textInput events, for appropriate keys. For mobile devices which have long-key-press behavior, the first key event with a repeat attribute value of 'true' shall serve as an indication of a long-key-press. The length of time that the key must be pressed in order to begin repeating is configuration-dependent.
Methods
getModifierState
Queries the state of a modifier using a key value. See also Modifier keys.
Parameters
keyArg of type DOMString

A modifier key value. Modifier keys defined in this specification are 'Alt', 'AltGraph', 'CapsLock', 'Control', 'Fn', 'Meta', 'NumLock', 'Scroll', 'Shift', and 'Win'. User agents may support additional implementation-specific modifier keys depending on the environment.

Note: If an application wishes to distinguish between right and left modifiers, this information could be deduced using keyboard events and KeyboardEvent.location.

Return Value

boolean

true if it is a modifier key and the modifier is activated, false otherwise.

No Exceptions
initKeyboardEvent

Initializes attributes of a KeyboardEvent object. This method has the same behavior as UIEvent.initUIEvent(). The value of UIEvent.detail remains undefined.

Parameters
typeArg of type DOMString

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

canBubbleArg of type boolean

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

cancelableArg of type boolean

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

viewArg of type views::AbstractView

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

keyArg of type DOMString

Specifies KeyboardEvent.key.

locationArg of type unsigned long

Specifies KeyboardEvent.location.

modifiersListArg of type DOMString

A white space separated list of modifier key values to be activated on this object. As an example, "Control Alt" must mark the control and alt modifiers as activated.

No Return Value
No Exceptions

Warning! Legacy keyboard event implementations may include two additional attributes, keyCode and charCode. The keyCode attribute indicates a numeric value associated with a particular key on a computer keyboard, while the charCode attribute indicates the ASCII value of the character associated with that key (which may or may not be the same as the keyCode value) and is applicable only to keys that produce a character value. In practice, keyCode and charCode are inconsistent across platforms and even the same implementation on different operating systems or using different localizations. DOM Level 3 Events does not define values for either keyCode or charCode, or behavior for charCode; content authors should use KeyboardEvent.key or KeyboardEvent.char instead, in conforming DOM Level 3 Events implementations. For more information, see the informative table in Key values, keyCode, and charCode.

Depending on the character generation device, keyboard events may or may not be generated.

Note: For compatibility with existing content, virtual keyboards, such as software keyboards on screen-based input devices, should produce the normal range of keyboard events, even though they do not possess physical keys.

The keyboard event types are listed below.

5.2.6.1 Keyboard Event Order

The keyboard events defined in this specification occur in a set order relative to one another, for any given key:

  1. keydown
  2. keypress (only for keys which produce a character value)
  3. If the key is depressed for a sustained period, the following events may repeat at an environment-dependent rate:
  4. Any default actions related to this key
  5. keyup

Keys associated with a character value must, under normal circumstances, produce a textInput event as well. The order of text events relative to keyboard events is as follows:

  1. keydown
  2. keypress (only for keys which produce a character value)
  3. If a character value is produced, textInput
  4. If the key is depressed for a sustained period, the following events may repeat at an environment-dependent rate:
  5. Any default actions associated with this key
  6. keyup

Note: Typically, any default actions associated with any particular key must be completed before the keyup event is dispatched, which may delay the keyup event slightly (though this is not likely to be a perceptible delay).

Warning! Because of hardware limitations, on some keyboard devices, the order between the text event and keyboard events may differ. For example, some mobile devices may dispatch the textInput event after the keyup event.

The target of a key event is the currently focused element which is processing the keyboard activity; this is often an HTML input element or a textual element which is editable, but may be an element defined by the host language to accept keyboard input for non-text purposes, such as the activation of a hotkey or trigger of some other behavior; if no suitable element is in focus, the event target will be the root element.

Note: The event target may change between different key events; for example, a keydown event on the 'Tab' key will likely have a different event target than the keyup event on the same keystroke.

keydown
Typekeydown
InterfaceKeyboardEvent
Sync / AsyncSync
BubblesYes
TargetElement
CancelableYes
Default actionVaries: textInput event; launch text composition system; blur and focus events; DOMActivate event; other event
Context info

A user agent must dispatch this event when a key is pressed down. The keydown event type is device dependent and relies on the capabilities of the input devices and how they are mapped in the operating system. This event type shall be generated after the keyboard mapping but before the processing of an input method editor, normally associated with the dispatching of a compositionstart, compositionupdate, or compositionend event. This event type must be dispatched before the keypress and keyup events event associated with the same key. Whether or not a keydown contributes to the generation of a text event is implementation dependent.

The default action of the keydown event depends upon the key:

  • if the key is associated with a character, the default action shall be to dispatch a textInput event with the character as the value of the TextEvent.data attribute
    • if the document's currently focused element can receive text (such as a form input or an editable text block), the default action shall be to dispatch a textInput event with the character as the value of the TextEvent.data attribute, and the focused element as the value of the Event.target attribute, and for that character to be appended to the text content of that element
  • if the key is associated with a text composition system, the default action shall be to launch that system
  • if the key is the tab key, the default action shall be to shift the document focus from the currently focused element (if any) to the new focused element, as described in Focus Event Types
  • if the key is the 'Enter' or 'Space' key and the current focus is on a state-changing element, the default action shall be to dispatch a click event, and a DOMActivate event if that event type is supported by the user agent (refer to activation triggers and behavior for more details)

If this event is canceled, the associated event types must not be dispatched, and the associated actions must not be performed.

Note: the keydown and keyup events are traditionally associated with detecting any key, not just those which produce a character value.

keypress
Typekeypress
InterfaceKeyboardEvent
Sync / AsyncSync
BubblesYes
TargetElement
CancelableYes
Default actionVaries: textInput event; launch text composition system; blur and focus events; DOMActivate event; other event
Context info

A user agent must dispatch this event when a key is pressed down, if and only if that key normally produces a character value. The keydown event type is device dependent and relies on the capabilities of the input devices and how they are mapped in the operating system. This event type shall be generated after the keyboard mapping but before the processing of an input method editor, normally associated with the dispatching of a compositionstart, compositionupdate, or compositionend event. This event type must be dispatched after the keydown event and before the keyup event associated with the same key.

Note: the keypress event is traditionally associated with detecting a character value rather than a physical key, and may not be available on all keys in some configurations.

Warning! the keypress event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type in favor of the textInput event type.

keyup
Typekeyup
InterfaceKeyboardEvent
Sync / AsyncSync
BubblesYes
TargetElement
CancelableYes
Default actionnone
Context info

A user agent must dispatch this event when a key is released. The keydown event type is device dependent and relies on the capabilities of the input devices and how they are mapped in the operating system. This event type shall be generated after the keyboard mapping. This event type must be dispatched after the keydown and keypress events event associated with the same key. Whether or not a keydown contributes to the generation of a text event is implementation dependent.

Note: the keydown and keyup events are traditionally associated with detecting any key, not just those which produce a character value.

5.2.7 Composition Event Types

This module defines the feature CompositionEvents 3.0 and depends on the feature UIEvents 3.0.

Composition Events provide a means for inputing text in a supplementary or alternate manner than by Keyboard Events, in order to allow the use of characters that may not be commonly available on keyboard. For example, Composition events may be used to add accents to characters despite their absence from standard US keyboards, to build up logograms of many Asian languages from their base components or categories, to select word choices from a combination of key presses on a mobile device keyboard, or to convert voice commands into text using a speech recognition processor. Refer to Keyboard events and key values for examples on how Composition Events are used in combination with keyboard events.

Conceptually, a composition session consists of one compositionstart event, one or more compositionupdate events, and one compositionend event, with the value of the data attribute persisting between each “stage” of this event chain during each session. While a composition session is active, keyboard events should not be dispatched to the DOM (i.e., the text composition system “swallows” the keyboard events), and only compositionupdate events may be dispatched to indicate the composition process.

Not all IME systems or devices expose the necessary data to the DOM, so the active composition string (the “Reading Window” or “candidate selection menu option”) may not be available through this interface, in which case the selection may be represented by the empty string.

Interface CompositionEvent (introduced in DOM Level 3)

The CompositionEvent interface provides specific contextual information associated with Composition Events.

To create an instance of the CompositionEvent interface, use the DocumentEvent.createEvent("CompositionEvent") method call.


IDL Definition

// Introduced in DOM Level 3:
interface CompositionEvent : UIEvent {
  readonly attribute DOMString       data;
  void                               initCompositionEvent(in DOMString typeArg, 
                                                          in boolean canBubbleArg, 
                                                          in boolean cancelableArg, 
                                                          in views::AbstractView viewArg, 
                                                          in DOMString dataArg);
};
                
Attributes
data of type DOMString, readonly

data holds the value of the characters generated by an input method. This may be a single Unicode character or a non-empty sequence of Unicode characters [Unicode]. Characters should be normalized as defined by the Unicode normalization form NFC, defined in [UAX #15]. This attribute may be null or contain the empty string.

Methods
initCompositionEvent
Initializes attributes of a CompositionEvent object. This method has the same behavior as UIEvent.initUIEvent(). The value of UIEvent.detail remains undefined.
Parameters
typeArg of type DOMString

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

canBubbleArg of type boolean

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

cancelableArg of type boolean

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

viewArg of type views::AbstractView

Refer to the UIEvent.initUIEvent() method for a description of this parameter.

dataArg of type DOMString

Specifies CompositionEvent.data.

No Return Value
No Exceptions

The composition event types are listed below.

5.2.7.1 Composition Event Order

The composition events defined in this specification occur in a set order relative to one another:

  1. compositionstart
  2. compositionupdate (multiple events)
  3. compositionend

Composition events which are not canceled and which do not have the empty string as a value produce a textInput event as well. The order of text events relative to composition events is as follows:

  1. compositionstart
  2. compositionupdate (multiple events)
  3. If a character value is produced, textInput
  4. compositionend
compositionstart
Typecompositionstart
InterfaceCompositionEvent
Sync / AsyncSync
BubblesYes
TargetElement
CancelableYes
Default actionLaunch text composition system
Context info

A user agent must dispatch this event when a text composition system is invoked in preparation for composing a passage of text. This event type is device-dependent, and may rely upon the capabilities of the text conversion system and how it is mapped into the operating system. When a keyboard is used to feed an input method editor, this event type is generated after a keydown event, but speech or handwriting recognition systems may send this event type without keyboard events. Some implemenations may populate the data attribute of the compositionstart event with the text currently selected in the document (for editing and replacement); otherwise, the value of the data attribute shall be the empty string.

This event must be dispatched immediately before a text composition system is launched, and before the DOM is modified due to the composition process. The default action of this event is to launch the appropriate text composition system. If this event is canceled, the text composition system must not be launched. Note that canceling the compositionstart event type is distinct from canceling the text composition system session (e.g. by hitting a cancel button or closing an IME window).

compositionupdate
Typecompositionupdate
InterfaceCompositionEvent
Sync / AsyncSync
BubblesYes
TargetElement
CancelableNo
Default actionnone
Context info

A user agent should dispatch this event when a text composition system updates its active text passage with a new character, which is added to the string in CompositionEvent.data. Note that some text composition systems may not expose this information to the DOM, in which case this event will not fire during the composition process. If the composition session is canceled, this event will be fired immediately before the compositionend event, and the CompositionEvent.data attribute will be set to null.

compositionend
Typecompositionend
InterfaceCompositionEvent
Sync / AsyncSync
BubblesYes
TargetElement
CancelableNo
Default actiontextInput event
Context info

A user agent must dispatch this event when a text composition system completes the composition of its active text passage, or cancels the composition process. If the result of the text composition system is not null and does not contain the empty string, this event type will be preceded by a textInput event type with the appropriate inputMethod value, such as DOM_INPUT_METHOD_IME, DOM_INPUT_METHOD_HANDWRITING, DOM_INPUT_METHOD_VOICE, or DOM_INPUT_METHOD_MULTIMODAL.

This event is dispatched immediately after the text composition system is completed (e.g. the IME closed, minimized, switched out of focus, or otherwise dismissed, with the focus switched back to the user agent).

5.2.7.2 Handwriting Recognition Systems

The following example describes a possible sequence of events when composing a text passage “text” with a handwriting recognition system, such as on a pen tablet, as modeled using Composition Events.

Example:

  1. compositionstart: ''
  2. [User writes word on tablet surface] compositionupdate: 'test'
  3. [User rejects first word-match suggestion, selects different match] compositionupdate: 'text'
  4. textInput: 'text' ("inputMethod": 'DOM_INPUT_METHOD_HANDWRITING')
  5. compositionend: 'text'

5.2.8 Mutation Events

This module defines the feature MutationEvents 3.0 and depends on the feature Events 3.0.

The mutation and mutation name event modules are designed to allow notification of any changes to the structure of a document, including attribute, text, or name modifications. It may be noted that none of the event types associated with the modules are designated as cancelable. This stems from the fact that it is very difficult to make use of existing DOM interfaces which cause document modifications if any change to the document might or might not take place due to cancelation of the resulting event. Although this is still a desired capability, it was decided that it would be better left until the addition of transactions into the DOM.

Many single modifications of the tree can cause multiple mutation events to be dispatched. Rather than attempt to specify the ordering of mutation events due to every possible modification of the tree, the ordering of these events is left to the implementation.

Warning! The MutationEvent interface was introduced in DOM Level 2 Events, but has not yet been completely and interoperably implemented across user agents. In addition, there have been critiques that the interface, as designed, introduces a performance and implementation challenge. A new specification is under development with the aim of addressing the use cases that mutation events solves, but in more performant manner. Thus, this specification describes mutation events for reference and completeness of legacy behavior, but deprecates the use of both the MutationEvent interface and the MutationNameEvent interface.

Interface MutationEvent (introduced in DOM Level 2)

The MutationEvent interface provides specific contextual information associated with Mutation events.

To create an instance of the MutationEvent interface, use the DocumentEvent.createEvent("MutationEvent") method call.


IDL Definition

// Introduced in DOM Level 2:
interface MutationEvent : Event {

  // attrChangeType
  const unsigned short      MODIFICATION                   = 1;
  const unsigned short      ADDITION                       = 2;
  const unsigned short      REMOVAL                        = 3;

  readonly attribute Node            relatedNode;
  readonly attribute DOMString       prevValue;
  readonly attribute DOMString       newValue;
  readonly attribute DOMString       attrName;
  readonly attribute unsigned short  attrChange;
  void               initMutationEvent(in DOMString typeArg, 
                                       in boolean canBubbleArg, 
                                       in boolean cancelableArg, 
                                       in Node relatedNodeArg, 
                                       in DOMString prevValueArg, 
                                       in DOMString newValueArg, 
                                       in DOMString attrNameArg, 
                                       in unsigned short attrChangeArg);
};
                
Definition group attrChangeType

An integer indicating in which way the Attr was changed.

Defined Constants
ADDITION
The Attr was just added.
MODIFICATION
The Attr was modified in place.
REMOVAL
The Attr was just removed.
Attributes
attrChange of type unsigned short, readonly

attrChange indicates the type of change which triggered the DOMAttrModified event. The values can be MODIFICATION, ADDITION, or REMOVAL.

attrName of type DOMString, readonly

attrName indicates the name of the changed Attr node in a DOMAttrModified event.

newValue of type DOMString, readonly

newValue indicates the new value of the Attr node in DOMAttrModified events, and of the CharacterData node in DOMCharacterDataModified events.

prevValue of type DOMString, readonly

prevValue indicates the previous value of the Attr node in DOMAttrModified events, and of the CharacterData node in DOMCharacterDataModified events.

relatedNode of type Node, readonly

relatedNode shall be used to identify a secondary node related to a mutation event. For example, if a mutation event is dispatched to a node indicating that its parent has changed, the relatedNode shall be the changed parent. If an event is instead dispatched to a subtree indicating a node was changed within it, the relatedNode shall be the changed node. In the case of the DOMAttrModified event it indicates the Attr node which was modified, added, or removed.

Methods
initMutationEvent

Initializes attributes of a MutationEvent object. This method has the same behavior as Event.initEvent().

Parameters
typeArg of type DOMString

Refer to the Event.initEvent() method for a description of this parameter.

canBubbleArg of type boolean

Refer to the Event.initEvent() method for a description of this parameter.

cancelableArg of type boolean

Refer to the Event.initEvent() method for a description of this parameter.

relatedNodeArg of type Node

Specifies MutationEvent.relatedNode.

prevValueArg of type DOMString

Specifies MutationEvent.prevValue. This value may be the empty string.

newValueArg of type DOMString

Specifies MutationEvent.newValue. This value may be the empty string.

attrNameArg of type DOMString

Specifies MutationEvent.attrName. This value may be the empty string.

attrChangeArg of type unsigned short

Specifies MutationEvent.attrChange. This value may be 0.

No Return Value
No Exceptions

The mutation event types are listed below.

DOMAttrModified
TypeDOMAttrModified
InterfaceMutationEvent
Sync / AsyncSync
BubblesYes
TargetElement
CancelableNo
Default actionnone
Context info

A user agent must dispatch this event after an Attr.value has been modified and after an Attr node has been added to or removed from an Element. The proximal event target of this event shall be the Element node where the change occurred. It is implementation dependent whether this event type occurs when the children of the Attr node are changed in ways that do not affect the value of Attr.value.

Warning! the DOMAttrModified event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type.

DOMCharacterDataModified
TypeDOMCharacterDataModified
InterfaceMutationEvent
Sync / AsyncSync
BubblesYes
TargetText, Comment, CDATASection, ProcessingInstruction
CancelableNo
Default actionnone
Context info

A user agent must dispatch this event after CharacterData.data or ProcessingInstruction.data have been modified, but the node itself has not been inserted or deleted. The proximal event target of this event shall be the CharacterData node or the ProcessingInstruction node.

Warning! the DOMCharacterDataModified event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type.

DOMNodeInserted
TypeDOMNodeInserted
InterfaceMutationEvent
Sync / AsyncSync
BubblesYes
TargetElement, Attr, Text, Comment, CDATASection, DocumentType, EntityReference, ProcessingInstruction
CancelableNo
Default actionnone
Context info

A user agent must dispatch this event type when a node other than an Attr node has been added as a child of another node. A user agent may dispatch this event when an Attr node has been added to an Element node (see note below). This event must be dispatched after the insertion has taken place. The proximal event target of this event shall be the node being inserted.

Note: for detecting attribute insertion, the DOMAttrModified event type should be used instead.

Warning! the DOMNodeInserted event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type.

DOMNodeInsertedIntoDocument
TypeDOMNodeInsertedIntoDocument
InterfaceMutationEvent
Sync / AsyncSync
BubblesNo
TargetElement, Attr, Text, Comment, CDATASection, DocumentType, EntityReference, ProcessingInstruction
CancelableNo
Default actionnone
Context info

A user agent must dispatch this event when a node has been inserted into a document, either through direct insertion of the node or insertion of a subtree in which it is contained; a user agent may optionally treat an Attr node as part of an Element's subtree. This event must be dispatched after the insertion has taken place. The proximal event target of this event shall be the node being inserted. If the node is being directly inserted, the event type DOMNodeInserted must occur before this event type.

Warning! the DOMNodeInsertedIntoDocument event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type.

DOMNodeRemoved
TypeDOMNodeRemoved
InterfaceMutationEvent
Sync / AsyncSync
BubblesYes
TargetElement, Attr, Text, Comment, CDATASection, DocumentType, EntityReference, ProcessingInstruction
CancelableNo
Default actionnone
Context info

A user agent must dispatch this event when a node other than an Attr node is being removed from its parent node. A user agent may dispatch this event when an Attr node is being removed from its ownerElement (see note below). This event must be dispatched before the removal takes place. The proximal event target of this event shall be the node being removed.

Note: for reliably detecting attribute removal, the DOMAttrModified event type should be used instead.

Warning! the DOMNodeRemoved event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type.

DOMNodeRemovedFromDocument
TypeDOMNodeRemovedFromDocument
InterfaceMutationEvent
Sync / AsyncSync
BubblesNo
TargetElement, Attr, Text, Comment, CDATASection, DocumentType, EntityReference, ProcessingInstruction
CancelableNo
Default actionnone
Context info

A user agent must dispatch this event when a node is being removed from a document, either through direct removal of the node or removal of a subtree in which it is contained; a user agent may optionally treat an Attr node as part of an Element's subtree. This event must be dispatched before the removal takes place. The proximal event target of this event type shall be the node being removed. If the node is being directly removed, the event type DOMNodeRemoved must occur before this event type.

Note: for reliably detecting attribute removal, the DOMAttrModified event type should be used instead.

Warning! the DOMNodeRemovedFromDocument event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type.

DOMSubtreeModified
TypeDOMSubtreeModified
InterfaceMutationEvent
Sync / AsyncSync
BubblesYes
TargetdefaultView, Document, DocumentFragment, Element, Attr
CancelableNo
Default actionnone
Context info

This is a general event for notification of all changes to the document. It can be used instead of the more specific mutation and mutation name events. It may be dispatched after a single modification to the document or, at the implementation's discretion, after multiple changes have occurred. The latter case should generally be used to accommodate multiple changes which occur either simultaneously or in rapid succession. The target of this event shall be the lowest common parent of the changes which have taken place. This event must be dispatched after any other events caused by the mutation(s) have occurred.

Warning! the DOMSubtreeModified event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type.

5.2.9 Mutation Name Event Types

This module defines the feature MutationNameEvents 3.0 and depends on the features MutationEvents 3.0 and Core 3.0.

Warning! The MutationNameEvent interface, introduced in an earlier draft of this specification, derives from the MutationEvent interface, which is deprecated in this specification. Thus, this specification describes the mutation name event types for completeness, but deprecates their use.

Interface MutationNameEvent (introduced in DOM Level 3)

The MutationNameEvent interface provides specific contextual information associated with Mutation name event types.

To create an instance of the MutationNameEvent interface, use the Document.createEvent("MutationNameEvent") method call.


IDL Definition

// Introduced in DOM Level 3:
interface MutationNameEvent : MutationEvent {
  readonly attribute DOMString       prevNamespaceURI;
  readonly attribute DOMString       prevNodeName;
  // Introduced in DOM Level 3:
  void                               initMutationNameEvent(in DOMString typeArg, 
                                                           in boolean canBubbleArg, 
                                                           in boolean cancelableArg, 
                                                           in Node relatedNodeArg, 
                                                           in DOMString prevNamespaceURIArg, 
                                                           in DOMString prevNodeNameArg);
};
                
Attributes
prevNamespaceURI of type DOMString, readonly

The previous value of the relatedNode's namespaceURI.

prevNodeName of type DOMString, readonly

The previous value of the relatedNode's nodeName.

Methods
initMutationNameEvent introduced in DOM Level 3

Initializes attributes of a MutationNameEvent object. This method has the same behavior as MutationEvent.initMutationEvent().

Parameters
typeArg of type DOMString

Refer to the MutationEvent.initMutationEvent() method for a description of this parameter.

canBubbleArg of type boolean

Refer to the MutationEvent.initMutationEvent() method for a description of this parameter.

cancelableArg of type boolean

Refer to the MutationEvent.initMutationEvent() method for a description of this parameter.

relatedNodeArg of type Node

Refer to the MutationEvent.initMutationEvent() method for a description of this parameter.

prevNamespaceURIArg of type DOMString

Specifies MutationNameEvent.prevNamespaceURI. This value may be null.

prevNodeNameArg of type DOMString

Specifies MutationNameEvent.prevNodeName.

No Return Value
No Exceptions

The mutation name event types are listed below.

DOMElementNameChanged
TypeDOMElementNameChanged
InterfaceMutationNameEvent
Sync / AsyncSync
BubblesYes
TargetElement
CancelableNo
Default actionnone
Context info

A user agent must dispatch this event after the namespaceURI and/or the nodeName of an Element node have been modified (e.g., the element was renamed using Document.renameNode()). The proximal event target of this event shall be the renamed Element node.

Warning! the DOMElementNameChanged event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type.

DOMAttributeNameChanged
TypeDOMAttributeNameChanged
InterfaceMutationNameEvent
Sync / AsyncSync
BubblesYes
TargetElement
CancelableNo
Default actionnone
Context info

A user agent must dispatch this event after the namespaceURI and/or the nodeName of a Attr node have been modified (e.g., the attribute was renamed using Document.renameNode()). The proximal event target of this event shall be the Element node whose Attr has been renamed.

Warning! the DOMAttributeNameChanged event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type.

6. Keyboard events and key values

This section contains necessary information regarding keyboard events:

Note: This section uses Serbian and Kanji characters which may be misrepresented or unavailable in the PDF version or printed version of this specification.

6.1 Keyboard Input

This section is informative

The relationship of each key to the complete keyboard has three separate aspects, each of which vary among different models and configurations of keyboards, particularly for locale-specific reasons:

This specification only defines the functional mapping, in terms of key values, but briefly describes key legends and keyboard layout for background.

6.1.1 Key Legends

This section is informative

The visual markings normally consist of one or more characters which a keystroke on that key will produce (such as 'F', '8', or 'ш'), or names or symbols which indicate that key's function (such as an upward-pointing arrow ⇧ indicating 'Shift', or the string 'Enter'). Keys are often referred to by this marking (e.g. “Press the 'Shift' and 'F' keys.”). However, the visual appearance of the key has no bearing on its digital representation, and in many configurations may be completely inaccurate; even the control and function keys, such as 'Enter', may be mapped to different functionality, or even mapped as character keys.

For historical reasons, the character keys are typically marked with the capital-letter equivalents of the character value they produce, e.g. the 'F' key (the key marked with the glyph 'F'), will produce the character value 'f' when pressing without an active modifier key ('Shift') or modifier state ('CapsLock').

Note that the key legends for function keys do not normally produce any characters, although the symbol may have a Unicode equivalent; for example, the 'Shift' key may bear the symbol ⇧, which has the Unicode code point '21E7', but pressing the 'Shift' key will not produce this character value, and there is no Unicode code point for 'Shift'.

6.1.2 Keyboard Layout

This section is informative

As with the key labels, the physical layout of the keys on the keyboard does not not affect the digital key value for any given key. It is outside the scope of this specification to provide key values based on keyboard layout, particularly since there are so many possible layouts for a keyboard, and since users can change the mapping of keys in their operating system, e.g. by selecting a Dvorak key mapping.

To illustrate the concept of keyboard layout mappings and its relation with keyboard events and key values, on the same keyboard (a PC/AT US keyboard), pressing the key labeled Q (with no modifier key activated) will produce different key values based on the mapping. With a typical US QWERTY keyboard layout mapping, it will produce the character 'q' (U+0071, Latin Small Letter Q). If the keyboard layout mapping is switched to a French mapping, pressing the same key will produce the character 'a' (U+0041, Latin Capital Letter A). If the keyboard layout mapping is switched to a Serbian (Cyrillic) mapping, pressing the same key will produce the character 'љ' (U+0459, Cyrillic Small Letter LJE).

However, the physical layout of the keys may be of interest to content authors developing games or other applications in which the location of the keys has an ergonomic relationship as the desired user interface controls, with little or no attention paid to the representational value of the key itself. For example, many games may use the keys 'A', 'S', 'D', and 'W' for 'left', 'down', 'right', and 'up' respectively. Content authors should provide a means for the user to assign such controller keys to a custom setting appropriate to their keyboard configurations. Implementations may provide a means for the user to more comprehensively map the keyboard to their customized keyboard layout, but this is beyond the scope of this specification.

Note: Key values should not be confused with scan codes, which are the low-level hexadecimal signals produced for each key by the keyboard driver software, and which are mapped at the operating system to a VK ("virtual key"), which in turn may be mapped to the user-defined key configuration. Key values are a high-level abstraction of that final mapping.

6.1.2.1 Desktop and Laptop Keyboards

In the case where a content author wishes to rely on the mechanical layout of a desktop or laptop keyboard, this specification suggests the keyboard configuration specified in ISO/IEC 9995, parts 2 and 3 [ISO-9995-2/3], which defines a common layout for primary, secondary, and auxiliary key mappings on a typical alphanumeric keyboard, as a common layout appropriate to some international uses.

Note: This keyboard layout is still, in essence, a QWERTY keyboard, and will not match the keyboards or configurations of many users. Content authors cannot rely upon any particular configuration, and should create content in an internationalized and localizable manner.

A graphical depiction of an ISO standard defining layouts of computer keyboards, ISO/IEC 9995, parts 2 and 3

Figure 3: A graphical depiction of an ISO standard defining layouts of computer keyboards, ISO 9995, parts 2 and 3

6.1.2.2 Mobile Keypads

In the case where a content author wishes to rely on the mechanical layout of a mobile keypad, this specification suggests the keyboard configuration specified in ISO/IEC 9995-8:2006 [ISO-9995-8], which defines a numeric keypad layout and secondary assignment of Unicode characters in the range \u0061..\u007A to the number keys 2 through 9, as a common layout appropriate to some international uses.

Note: This keypad layout, and in particular the distribution of letters is for English devices, and will not match the keypads or configurations of many users. Content authors cannot rely upon any particular configuration, and should create content in an internationalized and localizable manner.

A graphical depiction of an ISO standard defining layouts of numeric keypads, with distribution of letters on the keys, ISO/IEC 9995-8:2006

Figure 4: A graphical depiction of an ISO standard defining layouts of numeric keypads, with distribution of letters on the keys, ISO/IEC 9995-8:2006

6.1.2.3 Virtual Keyboards and Chording Keyboards

Virtual keyboards are software-based sets of keys, in a variety of different arrangements, commonly found on touch-screen devices; they are often modal, with the ability to switch between different dynamic sets of keys, such as alphabetic, numeric, or symbolic keys. Because of the lack of physical constraints, these keyboards may present the widest range of characters, including emoticons and other symbols, and may have keys not represented by Unicode [Unicode] or by the key values set defined in this specification. Wherever possible, however, virtual keyboards should produce the normal range of keyboard events and values, for ease of authoring and compatibility with existing content.

Chording keyboards, also know as chorded keysets or chord keyboards, are key input devices which produce values by pressing several keys in combination or sequence, normally to simulate a full range of characters or commands on a reduced set of keys, often for single-handed use. A chording keyboard may have additional mode keys to switch between key values, and the number and type of keys pressed to produce a key value will vary, but the final key values produced by such keyboards should match the range of key values described in this specification.

For these and other alternative modal keyboards, the key values 'Alphanumeric', 'CapsLock', 'NumLock', and 'SymbolLock' are recommended for the keys which switch between different modes.

6.2 Key Values

A key value is a DOMString that can be used to indicate any given key on a keyboard, regardless of position or state, by the value it produces. These key values may be used as return values for keyboard events generated by the implementation, or as input values by the content author to specify desired input (such as for keyboard shortcuts). This specification defines a set of common key values (called the Key Values Set), and rules for production of new key values.

Issue: Add mention of textInput and it's relationship to key values, per Ishida

Key values can be used to detect the value of a key which has been pressed, using the KeyboardEvent.key or KeyboardEvent.char attributes. Content authors can retrieve the character value of upper- or lower-case letters, number, symbols, or other character-producing keys, and also the key value of control keys, modifier keys, function keys, or other keys that do not generate characters; these values can be used for monitoring particular input strings, for detecting and acting on modifier key input in combination with other inputs (such as a mouse), for creating virtual keyboards, or for any number of other purposes.

Key values can also be used by content authors in string comparisons, as values for markup attributes (such as the HTML accesskey) in conforming host languages, or for other related purposes. A conforming host language should allow content authors to use either of the two equivalent string values for a key value: the character value, or the key value.

Issue: mention that content author should use case-insensitive matching to capture both "t" and "T" for hotkeys, etc.?

Note: While implementations are recommended to use the most relevant value for a key independently of the platform or keyboard layout mappings, content authors should not make assumption on the ability of keyboard devices to generate them. When using keyboard events and key values for shortcut-key combinations, content authors should consider using numbers and function keys (F4, F5, and so on) instead of letters ([DWW95]) given that most keyboard layouts will provide keys for those.

It is important to note that a key value does not indicate a specific key on the physical keyboard, nor does it reflect the character printed on the key; a key value indicates the current value of the event with consideration to the current state of all active keys and key input modes (including shift modes and dead keys), as reflected in the operating-system mapping of the keyboard and reported to the implementation. In other words, the key value for the key marked 'O' on a QWERTY keyboard has the key value 'o' in an unshifted state, 'O' in a shifted state, 'ö' in an unshifted state during a dead-key operation to add an umlaut diacritic, and 'Ö' in a shifted state during a dead-key operation to add an umlaut diacritic. Because a user may map their keyboard to an arbitrary custom configuration, the content author should not assume that a relationship exists between the shifted and unshifted states of a key and the majuscule form (uppercase or capital letters) and minuscule form (lowercase or small letters) of a character representation, but should instead use the value of the KeyboardEvent.key or KeyboardEvent.char attributes. The keyboard depicted in Figure 3 illustrates one possible set of key mappings on one possible keyboard layout; many others exist, both standard and idiosyncratic.

It is also important to note that there is not a one-to-one relationship between key event states and key values. A particular key value may be associated with multiple keys; for example, many standard keyboards contain more than one key with the 'Shift' key value (normally distinguished by the KeyboardEvent.location values DOM_KEY_LOCATION_LEFT and DOM_KEY_LOCATION_RIGHT) or '8' key value (normally distinguished by the KeyboardEvent.location values DOM_KEY_LOCATION_STANDARD and DOM_KEY_LOCATION_NUMPAD), and user-configured custom keyboard layouts may duplicate any key value in multiple key-state scenarios (note that KeyboardEvent.location is intended for standard keyboard layouts, and cannot always indicate a meaningful distinction).

Similarly, a given key event state may have different key values. For most keys which represent characters, such as the letter 'm' or the question mark ('?'), the KeyboardEvent.key and KeyboardEvent.char attributes will be the same. However, for printing control characters, such as the backspace/back key, the character value is distinct from the key value, with different values for the KeyboardEvent.key and KeyboardEvent.char attributes; see the Key Values Set for more details. Certain keys in some states, called modifier keys or control keys, have only a key value and no character value, such as the volume mute key, which has the KeyboardEvent.key attribute value 'VolumeMute' and the KeyboardEvent.char attribute value null.

Finally, the meaning of any given character representation is context-dependent and complex. For example, in some contexts, the asterisk (star) glyph ('*') represents a footnote or emphasis (when bracketing a passage of text); however, in some documents or executable programs it is equivalent to the mathematical multiplication operation, while in other documents or executable programs, that function is reserved for the multiplication symbol ('×', Unicode value U+00D7) or the Latin small letter 'x' (due to the lack of a multiplication key on many keyboard and the superficial resemblance of the glyphs '×' and 'x'). Thus, the semantic meaning or function of character representations is outside the scope of this specification.

6.2.1 Key Values and Unicode

The character values described in this specification are Unicode [Unicode] codepoints, and as such, have certain advantages.

The most obvious advantage is that it allows the content author to use the full range of internationalized language functionality available in the implementation, regardless of the limitations of the text input devices on the system. This opens up possibilities for virtual keyboards and Web-application-based input method editors.

Another benefit is that it allows the content author to utilize the Unicode general category properties programmatically.

With legacy keyboard event attributes such as keyCode and charCode, content authors are forced to filter key input using cryptic, platform- and implementation-specific numeric codes, with poor internationalization, such as the following pseudocode:

Example:


  
  if ( ( event.charCode == 45 || event.charCode == 36 ) ||
       ( event.charCode >= 48 && event.charCode <= 57 ) || 
       ( event.charCode >= 96 && event.charCode <= 105 ) ) {
    // minus sign, dollar sign, and numeric characters from keyboard and numpad
    ... 
  }
  else if ( ( event.charCode >= 65 && event.charCode <= 90 ) || 
            ( event.charCode >= 97 && event.charCode <= 122 ) ) {
    // alphabetic characters from Latin character set, A-Z, a-z
    ... 
  }
  else {
    ... 
  } 
            

With key values and regular expressions, however, content authors can support selective and intuitive ranges for key-based input, in a cross-platform manner with advanced internationalization support, such as the following pseudocode:

Example:


  if ( event.key == "-" || 
       event.key.match("\p{Sc}") || 
       event.key.match("\p{N}") ) {
    // minus sign, any currency symbol, and numeric characters (regardless of key location)
    ... 
  }
  else if ( event.key.match("\p{L}") ) {
    // alphabetic characters from any language, upper and lower case
    ... 
  }
  else {
    ... 
  } 
            

In addition, because Unicode categorizes each assigned code point into a group of code points used by a particular human writing system, even more advanced capabilities are possible. For example, a content author can match characters from a particular human script (e.g. Tibetan) using a regular expression such as \p{Tibetan}, to filter out other characters, or discover if a code point is in a certain code block (range of code points), using a regular expression like \p{InCyrillic}.

To facilitate this, implementations should support Unicode range detection using regular expressions, in a manner such as the Perl Compatible Regular Expressions (PCRE) [PCRE].

6.2.2 Modifier keys

Keyboard input uses modifier keys to change the normal behavior of a key. Like other keys, modifier keys generate keydown and keyup events, as shown in the example below. Some modifiers are activated while the key is being pressed down or maintained pressed such as 'Alt', 'Control', 'Shift', 'AltGraph', or 'Meta'. Others modifiers are activated depending on their state such as 'CapsLock', 'NumLock', or 'Scroll'. Change in the state happens when the modifier key is being pressed down. The KeyboardEvent interface provides convenient attributes for some common modifiers keys: KeyboardEvent.ctrlKey, KeyboardEvent.shiftKey, KeyboardEvent.altKey, KeyboardEvent.metaKey. Some operating systems simulate the 'AltGraph' modifier key with the combination of the "Alt and 'Control' modifier keys. Implementations are encouraged to use the 'AltGraph' modifier key.

The following example describes a possible sequence of events associated with the generation of the Unicode character Q (Latin Capital Letter Q, Unicode code point U+0051) on a PC/AT US keyboard using a US mapping:

Issue: Reformat example as table with "Event", "Returned value", and "Keys involved", per Ishida?

Example:

  1. keydown: 'Shift', shiftKey
  2. keydown: 'Q' (U+0051, Latin Capital Letter Q key), shiftKey
  3. textInput: 'Q'
  4. keyup: 'Q' (U+0051, Latin Capital Letter Q key), shiftKey
  5. keyup: 'Shift'

The following example describes an alternate sequence of keys to the example above, where the 'Shift' key is released before the 'Q' key. The key value for the key labeled 'Q' will revert to its unshifted value for the keyup event, after the production of the textInput event, thus:

Example:

  1. keydown: 'Shift', shiftKey
  2. keydown: 'Q' (U+0051, Latin Capital Letter Q key), shiftKey
  3. textInput: 'Q'
  4. keyup: 'Shift'
  5. keyup: 'q' (U+0071, Latin Small Letter Q key)

The following example describes a possible sequence of keys that does not generate a Unicode character (using the same configuration):

Example:

  1. keydown: 'Control', ctrlKey
  2. keydown: 'v' (U+0076, Latin Small Letter V key), ctrlKey
  3. keyup: 'v' (U+0076, Latin Small Letter V key), ctrlKey
  4. keyup: 'Control'

In some cases, modifier keys change the key value value for a key event. For example, on some MacOS keyboards, the key labeled 'delete' functions the same as the 'Backspace' key on the Windows OS when unmodified, but when modified by the 'Fn' key, acts as the 'Del' key, and the value of the key value must match the most appropriate function of the key in its current modified state.

6.2.3 Dead keys

Some keyboard input uses dead keys for the input of composed character sequences. Unlike the handwriting sequence, in which users enter the base character first, keyboard input requires to enter a special state when a dead key is pressed and emit the character(s) only when one of a limited number of “legal” base character is entered. (NOTE: the MacOS and Linux operating systems use input methods to process dead keys.)

The dead keys are represented in the key values set using combining diacritical marks. While Unicode combining characters always follow the handwriting sequence, with the combining character trailing the corresponding letter, typical deadkey input may reverse the sequence, with the combining character before the corresponding letter; for example, the word naïve, using the combining diacritic ¨, would be represented sequentially in Unicode as nai¨ve, but may be typed na¨ive. The sequence of keystrokes '\u0302' (Combining Circumflex Accent key) and '\u0065' (key marked with the Latin Small Letter E) will likely produce (on a PC/AT french keyboard using a french mapping and without any modifier activated) the Unicode character ê (Latin Small Letter E With Circumflex), as preferred by the Unicode Normalization Form NFC:

Example:

  1. keydown: \u0302 (Combining Circumflex Accent key)
  2. compositionstart: \u0302 (Combining Circumflex Accent key)
  3. compositionupdate: \u0302 (Combining Circumflex Accent key)
  4. keyup: \u0302 (Combining Circumflex Accent key)
  5. keydown: 'ê' (U+00EA, LATIN SMALL LETTER E WITH CIRCUMFLEX)
    Note: the key value will not be 'e' (Latin Small Letter E key) under normal circumstances, because the value delivered to the user agent will already be modified by the dead key operation.
    Issue: is this correct for the case of composition events?
  6. compositionend: 'ê'
  7. textInput: 'ê' ("inputMethod": 'DOM_INPUT_METHOD_IME')
  8. keyup: 'e' (U+0065, Latin Small Letter E key)

This process may be aborted when a user types an unsupported base character (that is, a base character for which the which the active diacritical mark is not available) after pressing a dead key:

Example:

  1. keydown: \u0302 (Combining Circumflex Accent key)
  2. compositionstart: \u0302 (Combining Circumflex Accent key)
  3. compositionupdate: \u0302 (Combining Circumflex Accent key)
  4. keyup: \u0302 (Combining Circumflex Accent key)
  5. keydown: 'q' (U+0071, The Latin Small Letter Q key)
  6. compositionend: ''
  7. textInput: 'q' ("inputMethod": 'DOM_INPUT_METHOD_KEYBOARD')
  8. keyup: 'q' (U+0071, The Latin Small Letter Q key)

6.2.4 Input Method Editors

This specification includes a model for input method editors (IMEs), through the CompositionEvent interface and events. However, composition events and keyboard events do not necessarily map as a one-to-one relationship. As an example, receiving a keydown for the 'Accept' key value does not necessarily imply that the text currently selected in the IME is being accepted, but indicates only that a keystroke happened, disconnected from the IME Accept functionality (which would normally result in a compositionend event in most IME systems). Keyboard events cannot be used to determine the current state of the input method editor, which should be obtained through the data attribute of the CompositionEvent interface. Additionally, IME systems and devices vary in their functionality, and in which keys are used for activating that functionality, such that the 'Convert' and 'Accept' keys may be represented by other available keys.

Keyboard events correspond to the events generated by the input device after the keyboard layout mapping but before the processing of the input method editor.

The following example describes a possible sequence of keys to generate the Unicode character 市 (Kanji character, part of CJK Unified Ideographs) using Japanese input methods. This example assumes that the input method editor is activated and in the Japanese-Romaji input mode. The keys 'Convert' and 'Accept' may be replaced by others depending on the input device in use and the configuration of the IME, e.g. it could be respectively U+0020 (Space key) and 'Enter'. Note:'詩' ("poem") and '市' ("city") are homophones, both pronounced “shi”, so the user must use the 'Convert' key to select the proper option.

Example:

  1. keydown: 's' (U+0073, Latin Small Letter S key)
  2. compositionstart: ''
  3. keyup: 's' (U+0073, Latin Small Letter S key)
  4. keydown: 'i' (U+0069, Latin Small Letter I key)
  5. keyup: 'i' (U+0069, Latin Small Letter I key)
  6. keydown: 'Convert'
  7. compositionupdate: '詩'
  8. keyup: 'Convert'
  9. keydown: 'Convert'
  10. compositionupdate: '市'
  11. keyup: 'Convert'
  12. keydown: 'Accept'
  13. compositionend: '市'
  14. textInput: '市' ("inputMethod": 'DOM_INPUT_METHOD_IME')
  15. keyup: 'Accept'

IME composition may also be canceled as in the following example, with conditions identical to the previous example. The key 'Cancel' may also be replaced by others depending on the input device in use and the configuration of the IME, e.g. it could be "\u001B" (Escape key).

Example:

  1. keydown: 's' (U+0073, Latin Small Letter S key)
  2. compositionstart: ''
  3. keyup: 's' (U+0073, Latin Small Letter S key)
  4. keydown: 'i' (U+0069, Latin Small Letter I key)
  5. keyup: 'i' (U+0069, Latin Small Letter I key)
  6. keydown: 'Convert'
  7. compositionupdate: '詩'
  8. keyup: 'Convert'
  9. keydown: 'Convert'
  10. compositionupdate: '市'
  11. keyup: 'Convert'
  12. keydown: 'Cancel'
  13. compositionupdate: ''
  14. compositionend: ''
  15. keyup: 'Cancel'

NOTE: Some input method editors (such as on the MacOS operating system) may set an empty string to the composition data attribute before canceling a composition.

6.2.4.1 Input Method Editor mode keys

Some keys on certain devices are intended to activate input method editor functionality, or to change the mode of an active input method editor. Custom keys for this purpose may be defined for different devices or language modes; the keys defined in this specification for this purpose are: Alphanumeric, CodeInput, FinalMode, HangulMode, HanjaMode, Hiragana, JapaneseHiragana, JapaneseKatakana, JapaneseRomaji, JunjaMode, KanaMode, KanjiMode, Katakana, and RomanCharacters. When one of these keys is pressed, and no IME is currently active, the appropriate IME, shall be activated in the mode indicated by the key (if available); if an IME is already active when the key is pressed, the active IME may change to the indicated mode, or a different IME may be launched, or the key may be ignored, on a device- and application-specific basis.

This specification also defines other keys which are intended for operation specifically with input method editors: Accept, AllCandidates, Cancel, Convert, Compose, FullWidth, HalfWidth, NextCandidate, Nonconvert, and PreviousCandidate. The functions of these keys are not defined in this specification; refer to other resources for details on input method editor functionality.

Note that keys with input method editor functions are note restricted to that purpose, and may have other device- or implementation-specific purposes, as well.

6.2.5 Default actions and cancelable keyboard events

Canceling the default action of a keydown event must not affect its respective keyup event, but it must prevent the respective textInput event from being generated. The following example describes a possible sequence of keys to generate the Unicode character Q (Latin Capital Letter Q) on a PC/AT US keyboard using a US mapping:

Example:

  1. keydown: 'Shift', shiftKey
  2. keydown: 'Q' (U+0051, Latin Capital Letter Q key), shiftKey
  3. The default action of the keydown event is prevented, e.g. by invoking Event.preventDefault() during the dispatch of the keydown event object
  4. No textInput event is generated
  5. keyup: 'Q' (U+0051, Latin Capital Letter Q key), shiftKey
  6. keyup: 'Shift'

If the key is a modifier key, the keystroke must still be taken into account for the modifiers states. The following example describes a possible sequence of keys to generate the Unicode character Q (Latin Capital Letter Q) on a PC/AT US keyboard using a US mapping:

Example:

  1. keydown: 'Shift', shiftKey
  2. The default action of the keydown event is prevented, e.g. by invoking Event.preventDefault() during the dispatch of the keydown event object
  3. keydown: 'Q' (U+0051, Latin Capital Letter Q key), shiftKey
  4. textInput: 'Q'
  5. keyup: 'Q' (U+0051, Latin Capital Letter Q key), shiftKey
  6. keyup: 'Shift'

Issue: does this make sense? shouldn't the shift modifier attribute be canceled? needs testing...

If the key is part of a sequence of several keystrokes, whether it is a dead key or it is contributing to an Input Method Editor sequence, the keystroke shall be ignored (not taken into account) only if the default action is canceled on the keydown event. Canceling a dead key on a keyup event has no effect on textInput events. The following example uses the keystrokes U+0302 (Combining Circumflex Accent key) and the key marked 'e' (U+0065, Latin Small Letter E key) (on a PC/AT french keyboard using a french mapping and without any modifier activated):

LATIN SMALL LETTER E WITH ACUTE' (U+00E9)

Example:

  1. keydown: U+0302 (Combining Circumflex Accent key)
  2. The default action of the keydown event is prevented, e.g. by invoking Event.preventDefault() during the dispatch of the keydown event object
  3. keyup: U+0302 (Combining Circumflex Accent key)
  4. keydown: 'é' (U+00E9, LATIN SMALL LETTER E WITH ACUTE)
  5. textInput: 'é'
  6. keyup: 'é'

6.2.6 Guidelines for selecting and defining key values

Note: This section is normative.

The list of key values contained in this specification is not exhaustive, and input devices may have to define their own key values. Consider the current function of the key (i.e., with modifiers), taking into consideration the keyboard layout mapping in use, to determine if the key is represented by the set of defined key values, if a corresponding Unicode character exists from which a key value may be derived, or if a new key value must be defined. The following algorithm determines the key value and character value to use:

  1. If the primary current function of the key is to generate a character, then:
    1. If there exists an appropriate character in the key values set, then:
      1. the KeyboardEvent.key attribute must be a string consisting of the key value of that character; and
      2. the KeyboardEvent.char attribute must be a string consisting of the char value of that character.
    2. If there is no appropriate key value in the key values set, and there exists an appropriate Unicode code point, then:
      1. the KeyboardEvent.key attribute must be a string consisting of the char value of that character; and
      2. the KeyboardEvent.char attribute must be a string consisting of the char value of that character.
  2. If the primary current function of the key is to serve as a function key, then:
    1. If there exists an appropriate key value in the key values set, then:
      1. the KeyboardEvent.key attribute must be a string consisting of the key value of that character; and
      2. the KeyboardEvent.char attribute must be null.
    2. If there is no appropriate key value in the key values set, then a key value must be devised. The key value should be as human friendly as possible and must not contain whitespace characters. The value must be composed only of characters in the ranges \u0030..\u0039, \u0041..\u005A, or \u0061..\u007A, and must begin with a character in the range \u0041..\u005A.

To Do: Update the algorithm example to match the change in the algorithm.

Examples:

  • On a PC/AT US keyboard with a right-handed single-hand Dvorak keyboard mapping, the key labeled 'Q' maps to the key values '5' (unmodified) and '%' (shifted). The primary function of this key is to generate the character '5' (U+0035). Since this character is a character (in Unicode general category Nd), the KeyboardEvent.key and KeyboardEvent.char attribute values for the unmodified key will be '5'.
  • On a French PC keyboard with a standard French mapping, the primary function of the '^' key is as a dead key for the circumflex diacritical mark. This corresponds to the combining Unicode character U+0302. Since this character is in general category Mn, the key value shall be U+0302.
  • On a Korean PC keyboard with a standard Korean mapping, the primary function of the 'Ha/En' key is to switch between Hangul and English input. The predefined key value list has an appropriate entry for this key, 'HangulMode', so this shall be the key value.
  • On some models of mobile devices, the primary function of the key with a picture of a calendar on it is to launch the calendaring program. Since there is no Unicode character that corresponds to this function, and there is no appropriate entry in the predefined key value list, a new value may be devised, such as 'Calendar'.

6.2.7 Key Values Set

This section defines a list of key values which implementations must support, at a minimum, in addition to support for the full range of Unicode [Unicode] codepoints. Implementations may support additional key values, in a manner conforming to the guidelines for selecting and defining key values. Each key value defines one or both of the following: a character value and a key value. The KeyboardEvent.key attribute of an event must always contain one of these control key or character values (even if the value is 'Unidentified'), and the KeyboardEvent.char attribute must have a value if the key represents a printable character. If the key represents one of the set of printable control characters which has a Unicode character entry, such as the tab key, the KeyboardEvent.key attribute must have the key value (e.g. 'Tab'), while the KeyboardEvent.char attribute must have the Unicode character value equivalent (e.g. \u0009). This affords content authors the opportunity to deal with the key as a control key or as direct input into the text stream.

The key values defined in this specification are based on the sets of keycodes from the java.awt.event.KeyEvent interface of the Java Platform, Standard Edition 6 API Specification [KeyEvent for Java], and the System.Windows.Forms.Keys key enumeration of the Microsoft .NET Framework 4.0 Class Library [Keys enumeration for .Net]. The character values defined in this specification are derived from the Unicode standard [Unicode].

Note: The key names 'NumPad0', 'NumPad1', 'NumPad2', 'NumPad3', 'NumPad4', 'NumPad5', 'NumPad6', 'NumPad7', 'NumPad8', and 'NumPad9', found in some keyboard enumeration sets, are not distinguished from other numerical key values in this set; a content author may use the KeyboardEvent.location attribute to discover if a key originated from the numeric keypad.

Future versions of this specification may include key values not included here, which have become common since the publication of this specification.

In the following list, character values for printing control characters are described as a character escape, for convenience, using the JavaScript notation for escapes.

Note: There are special internationalization considerations for ECMAScript escaped characters. CharMod conformance [CharMod] expects the use of code points rather than surrogate pairs in escapes; ECMAScript escaped characters use surrogate pairs for characters outside the Basic Multilingual Plane ("\uD84E\uDDC2" for 𣧂, a Chinese character meaning “untidy”), rather than C-style fixed-length characters ("\U000239c2" for 𣧂) or delimited escapes such as Numeric Character References ("&#x239C2;"). Characters escaped in this manner:

  • are based on UTF-16 encoding, in that it uses surrogate pairs for values outside the Basic Multilingual Plane
  • are expressed using surrogate pairs, which makes it difficult for a human to look up the value, and may require unnecessary overhead for machine processing; this can also cause problems with software written in the incorrect belief that Unicode is a 16-bit character set
  • are problematic for characters on supplementary planes (emoji, or Chinese characters on plane 2), some of which may be expected to be input using a keyboard
  • may not be suitable for Java or C, which use different escaping mechanisms (could be solved with a normalizing method)
Legend for the following list:
  • Key values are denoted with a blue background, and are the first term in a set
  • Character values, where present, are denoted with a green background, and follow the key value.
'Accept'
The Accept (Commit, OK) key.
'Add'
The Add key.
'Again'
The Again key.
'AllCandidates'
The All Candidates key.
'Alphanumeric'
The Alphanumeric key.
'Alt'
The Alt (Menu) key.
'AltGraph'
The Alt-Graph key.
'Apps'
The Application key.
'Attn'
The ATTN key.
'BrowserBack'
The Browser Back key.
'BrowserFavorites'
The Browser Favorites key.
'BrowserForward'
The Browser Forward key.
'BrowserHome'
The Browser Home key.
'BrowserRefresh'
The Browser Refresh key.
'BrowserSearch'
The Browser Search key.
'BrowserStop'
The Browser Stop key.
'Camera'
The Camera key.
'CapsLock'
The Caps Lock (Capital) key.
'Clear'
The Clear key.
'CodeInput'
The Code Input key.
'Compose'
The Compose key.
'Control'
The Control (Ctrl) key.
'Crsel'
The Crsel key.
'Convert'
The Convert key.
'Copy'
The Copy key.
'Cut'
The Cut key.
'Decimal'
The Decimal key.
'Divide'
The Divide key.
'Down'
The Down Arrow key.
'DownLeft'
The diagonal Down-Left Arrow key.
'DownRight'
The diagonal Down-Right Arrow key.
'Eject'
The Eject key.
'End'
The End key.
'Enter'
The Enter key. Note: This key value must also be used for the Return (Macintosh numpad) key.
'EraseEof'
The Erase EOF key.
'Execute'
The Execute key.
'Exsel'
The Exsel key.
'Fn'
The Function switch key.
'F1'
The F1 key.
'F2'
The F2 key.
'F3'
The F3 key.
'F4'
The F4 key.
'F5'
The F5 key.
'F6'
The F6 key.
'F7'
The F7 key.
'F8'
The F8 key.
'F9'
The F9 key.
'F10'
The F10 key.
'F11'
The F11 key.
'F12'
The F12 key.
'F13'
The F13 key.
'F14'
The F14 key.
'F15'
The F15 key.
'F16'
The F16 key.
'F17'
The F17 key.
'F18'
The F18 key.
'F19'
The F19 key.
'F20'
The F20 key.
'F21'
The F21 key.
'F22'
The F22 key.
'F23'
The F23 key.
'F24'
The F24 key.
'FinalMode'
The Final Mode (Final) key used on some asian keyboards.
'Find'
The Find key.
'FullWidth'
The Full-Width Characters key.
'HalfWidth'
The Half-Width Characters key.
'HangulMode'
The Hangul (Korean characters) Mode key.
'HanjaMode'
The Hanja (Korean characters) Mode key.
'Help'
The Help key.
'Hiragana'
The Hiragana (Japanese Kana characters) key.
'Home'
The Home key.
'Insert'
The Insert (Ins) key.
'JapaneseHiragana'
The Japanese-Hiragana key.
'JapaneseKatakana'
The Japanese-Katakana key.
'JapaneseRomaji'
The Japanese-Romaji key.
'JunjaMode'
The Junja Mode key.
'KanaMode'
The Kana Mode (Kana Lock) key.
'KanjiMode'
The Kanji (Japanese name for ideographic characters of Chinese origin) Mode key.
'Katakana'
The Katakana (Japanese Kana characters) key.
'LaunchApplication1'
The Start Application One key.
'LaunchApplication2'
The Start Application Two key.
'LaunchMail'
The Start Mail key.
'Left'
The Left Arrow key.
'Menu'
The Menu key.
'Meta'
The Meta key. Note: This key value shall be also used for the Apple Command key.
'MediaNextTrack'
The Media Next Track key.
'MediaPlayPause'
The Media Play Pause key.
'MediaPreviousTrack'
The Media Previous Track key.
'MediaStop'
The Media Stop key.
'ModeChange'
The Mode Change key.
'NextCandidate'
The Next Candidate function key.
'Nonconvert'
The Nonconvert (Don't Convert) key.
'NumLock'
The Number Lock key.
'PageDown'
The Page Down (Next) key.
'PageUp'
The Page Up key.
'Paste'
The Paste key.
'Pause'
The Pause key.
'Play'
The Play key.
'Power'
The Power key. Note: Some devices may not expose this key to the operating environment.
'PreviousCandidate'
The Previous Candidate function key.
'PrintScreen'
The Print Screen (PrintScrn, SnapShot) key.
'Process'
The Process key.
'Props'
The Props key.
'Right'
The Right Arrow key.
'RomanCharacters'
The Roman Characters function key.
'Scroll'
The Scroll Lock key.
'Select'
The Select key.
'SelectMedia'
The Select Media key.
'Separator'
The Separator key.
'Shift'
The Shift key.
'Soft1'
The Soft1 key.
'Soft2'
The Soft2 key.
'Soft3'
The Soft3 key.
'Soft4'
The Soft4 key.
'Stop'
The Stop key.
'Subtract'
The Subtract key.
'SymbolLock'
The Symbol Lock key.
'Up'
The Up Arrow key.
'UpLeft'
The diagonal Up-Left Arrow key.
'UpRight'
The diagonal Up-Right Arrow key.
'Undo'
The Undo key.
'VolumeDown'
The Volume Down key.
'VolumeMute'
The Volume Mute key.
'VolumeUp'
The Volume Up key.
'Win'
The Windows Logo key.
'Zoom'
The Zoom key.
'Backspace'
\u0008
The Backspace (Back) key. Note: This key value shall be also used for the key labeled 'delete' MacOS keyboards when not modified by the 'Fn' key.
'Tab'
\u0009
The Horizontal Tabulation (Tab) key.
'Cancel'
\u0018
The Cancel key.
'Esc'
\u001B
The Escape (Esc) key.
'Spacebar'
\u0020
The Space (Spacebar) key:  .
'Del'
\u007F
The Delete (Del) Key. Note: This key value shall be also used for the key labeled 'delete' MacOS keyboards when modified by the 'Fn' key.
'DeadGrave'
\u0300
The Combining Grave Accent (Greek Varia, Dead Grave) key.
'DeadEacute'
\u0301
The Combining Acute Accent (Stress Mark, Greek Oxia, Tonos, Dead Eacute) key.
'DeadCircumflex'
\u0302
The Combining Circumflex Accent (Hat, Dead Circumflex) key.
'DeadTilde'
\u0303
The Combining Tilde (Dead Tilde) key.
'DeadMacron'
\u0304
The Combining Macron (Long, Dead Macron) key.
'DeadBreve'
\u0306
The Combining Breve (Short, Dead Breve) key.
'DeadAboveDot'
\u0307
The Combining Dot Above (Derivative, Dead Above Dot) key.
'DeadUmlaut'
\u0308
The Combining Diaeresis (Double Dot Abode, Umlaut, Greek Dialytika, Double Derivative, Dead Diaeresis) key.
'DeadAboveRing'
\u030A
The Combining Ring Above (Dead Above Ring) key.
'DeadDoubleacute'
\u030B
The Combining Double Acute Accent (Dead Doubleacute) key.
'DeadCaron'
\u030C
The Combining Caron (Hacek, V Above, Dead Caron) key.
'DeadCedilla'
\u0327
The Combining Cedilla (Dead Cedilla) key.
'DeadOgonek'
\u0328
The Combining Ogonek (Nasal Hook, Dead Ogonek) key.
'DeadIota'
\u0345
The Combining Greek Ypogegrammeni (Greek Non-Spacing Iota Below, Iota Subscript, Dead Iota) key.
'DeadVoicedSound'
\u3099
The Combining Katakana-Hiragana Voiced Sound Mark (Dead Voiced Sound) key.
'DeadSemivoicedSound'
\u309A
The Combining Katakana-Hiragana Semi-Voiced Sound Mark (Dead Semivoiced Sound) key.
'Unidentified'
This key value is used when an implementations is unable to identify another key value, due to either hardware, platform, or software constraints. Warning! Conforming implementation must only use this key value when there is no way for the implementation to detect the key value, and does not indicate a conforming implementation by itself.

6.2.8 Key values, keyCode, charCode, and which

Browser support for keyboards has traditionally relied on three ad-hoc attributes, keyCode, charCode, and which. All three of these attributes return a numerical code that represents some aspect of the key pressed: keyCode is an index of the key itself; charCode is the ASCII value of the character keys; which is the character value where available and otherwise the key index. The values for these attributes, and the availability of the attribute, is inconsistent across platforms, keyboard languages and layouts, user agents, versions, and even event types. A significant amount of legacy content, including script libraries, relies upon detecting the user agent and acting accordingly, and any changes to keyCode, charCode, or which risk breaking as much content as they fix or enable. Additionally, these attributes are not suitable for international usage, or accessibility concerns.

Therefore, this specification does not normatively define the values for the keyCode, charCode, or which attributes, relying instead only on the more robust key values, which can be used safely and consistently in any user agent which conforms to this specification.

However, for the purpose of documenting the current state of these attributes and their relation to equivalent key values, this specification refers to the Legacy Keyboard Event Properties [KeyProps] WG Note, which contains an informative reference table that documents some common values for the keyCode and charCode properties in different implementations.

Additionally, in order to provide raw access to any available environment-specific keys, absent the effect of modifier keys, the KeyboardEvent interface does define the legacy KeyboardEvent.keyCode attribute, but the value of the attribute may vary between implementations and even between the same implementation on different operating systems. Normally, for modified values, the KeyboardEvent.key attribute should be used instead of the KeyboardEvent.keyCode attribute.

This specification does not define the charCode or which attributes on the KeyboardEvent interface, though they may be present in user agents for compatibility with legacy content. The KeyboardEvent.char attribute should be used instead of the charCode attribute.

Appendix A: Extending Events

This section is informative

A.1 Introduction

This specification defines several interfaces and many events; however, this is not an exhaustive set of events for all purposes. To allow content authors and implementers to add desired functionality, this specification provides two mechanisms for extend this set of interfaces and events without creating conflicts: custom events and implementation-specific extensions.

A.2 Custom Events

A script author may wish to define an application in terms of functional components, with event types that are meaningful to the application architecture. The content author can use the CustomEvent interface to create their own events appropriate to the level of abstraction they are using.

Example: A content author may have created an application which features a dynamically generated bar chart. This bar chart is meant to be updated every 5 minutes, or when a feed shows new information, or when the user refreshes it manually by clicking a button. There are several handlers that have to be called when the chart needs to be updated: the application must fetch the most recent data, show an icon to the user that the event is being updated, and rebuild the chart. To manage this, the content author can choose to create a custom "updateChart" event, which is fired whenever one of the trigger conditions is met:


  var chartData = ...;
  var evt = document.createEvent("CustomEvent");
  evt.initCustomEvent( "updateChart", true, false, { data: chartData });
  document.documentElement.dispatchEvent(evt);          
        

A.3 Implementation-Specific Extensions

While a new event is being designed and prototyped, or when an event is intended for implementation-specific functionality, it is desirable to distinguish it from standardized events. Implementors should prefix event types specific to their implementations with a short string to distinguish it from the same event in other implementations and from standardized events. This is similar to the vendor-specific keyword prefixes in CSS, though without the dashes ("-") used in CSS, since that can cause problems when used as an attribute name in Javascript.

Example: A particular browser vendor, "FooCorp", may wish to introduce a new event, "jump". This vendor implements "fooJump" in their browser, using their vendor-specific prefix, foo. Early adopters start experimenting with the event, using someElement.addEventListener( "fooJump", doJump, false ), and provide feedback to FooCorp, who change the behavior of "fooJump" accordingly.

After some time, another vendor, "BarOrg", decides they also want the functionality, but implement it slightly differently, so they use their own vendor-specific prefix, bar in their event type name, "barJump". Content authors experimenting with this version of the "jump" event type register events with BarOrg's event type name. Content authors who wish to write code that accounts for both browsers can either register each event type separately with specific handlers, or use the same handler and switch on the name of the event type; thus, early experiments in different codebases do not conflict, and the early adopter is able to write easily-maintained code for multiple implementations.

Eventually, as the feature matures, the behavior of both browsers stabilize and may converge due to content author and user feedback or through formal standardization; as this stabilization occurs, and risk of conflicts decrease, content authors can remove the forked code, and use the "jump" event type name (even before it is formally standardized) using the same event handler and the more generic registration method someElement.addEventListener( "jump", doJump, false ).

A.3.1 Known Implementation-Specific Prefixes

At the time of writing, the following event-type name prefixes are known to exist:

Prefix Web Engine (Organization)
moz, Moz Gecko (Mozilla)
ms, MS Trident (Microsoft)
o, OIssue: is this correct? Presto (Opera Software)
webkit WebKit (Apple, Google, others)

Appendix B: Security Considerations

This appendix discusses security considerations for DOM Level 3 Events implementations. The discussion is limited to security issues that arise directly from implementation of the event model, APIs and events defined in this specification. Implementations typically support other features like scripting languages, other APIs and additional events not defined in this document; these features constitute an unknown factor and are out of scope of this document. Implementers should consult the specifications of such features for their respective security considerations.

Many of the event types defined in this specification are dispatched in response to user actions. This allows malicious event listeners to gain access to information users would typically consider confidential, e.g., typos they might have made when filling out a form, if they reconsider their answer to a multiple choice question shortly before submitting a form, their typing rate or primary input mechanism. In the worst case, malicious event listeners are able to capture all user interactions and submit them to a third party through means, while not defined in DOM Level 3 Events, generally available in DOM implementations, such as the XMLHttpRequest interface.

In DOM implementations that support facilities to load external data, events like the error event can provide access to sensitive information about the environment of the computer system or network; an example would be a malicious HTML document that attempts to embed a resource on the local network or the localhost on different ports; an embedded DOM application could then listen for error and load events to determine which other computers in a network are accessible from the local system or which ports are open on the system to prepare further attacks.

An implementation of DOM Level 3 Events alone is generally insufficient to perform attacks of this kind and the security considerations of the facilities that possibly support such attacks apply. For conformance with this specification, DOM implementations may take reasonable steps to ensure that DOM applications do not get access to confidential or sensitive information, for example, they may choose to dispatch no load events to nodes that attempt to embed resources on the local network.

The DOMImplementation.hasFeature() method allows content authors to retrieve information about which event types the implementation supports, including event types not defined in this specification. Which event types a DOM Level 3 Events implementation supports can depend on configuration settings or on additional software modules available to the implementation.

Appendix C: Changes

C.1 Changes between DOM Level 2 Events and DOM Level 3 Events

Numerous clarifications to the interfaces and event types have been made. The HTMLEvents module is no longer defined in this document. The event types focus and blur have been added to the UIEvent module, the event type dblclick has been added to the MouseEvent module. This new specification provides a better separation between the DOM event flow, the event types, and the DOM interfaces.

C.1.1 Changes to DOM Level 2 event flow

This new specification introduced the following new concepts in the event flow:

  • ordering of event listeners: event listeners are now ordered while ordering was unspecified in DOM Level 2 Events.
  • the event flow now includes the defaultView (or window), to reflect existing implementations.

C.1.2 Changes to DOM Level 2 event types

Many clarifications have been made on the event types. The conformance is now explicitly defined against the event types, and not only in terms of interfaces required by the event types. Support for the features "BasicEvents", "TextEvents", "KeyboardEvents", and "MutationNameEvents" have been introduced.

In the most recent drafts of this specification, "MutationEvents" and "MutationNameEvents" have been deprecated. Support for namespaced events, present in early drafts of this specification, has been removed.

For user agents which support the DOMNodeInserted and DOMNodeRemoved event types, this specification no longer requires that the event type be fired for Attr nodes.

The resize event type no longer bubbles, reflecting existing implementations.

C.1.3 Changes to DOM Level 2 Events interfaces

Interface Event
The Event interface has one new attribute, Event.defaultPrevented, and one new method, Event.stopImmediatePropagation().
Event.timeStamp is now a Number in the ECMAScript binding; a proposed correction to make the same change in [DOM3 Core] is forthcoming.
DOM Level 3 Events considers the Event.type attribute to be case-sensitive, while DOM Level 2 Events considers Event.type to be case-insensitive.
Interface EventTarget
The method EventTarget.dispatchEvent() was modified.
Interface MouseEvent
The MouseEvent interface has one new method MouseEvent.getModifierState().
Exception EventException
The DISPATCH_REQUEST_ERR constant has been added.

C.1.4 New Interfaces

The interfaces CustomEvent, FocusEvent, TextEvent, KeyboardEvent, CompositionEvent, MutationNameEvent, and WheelEvent were added to the Events module.

C.2 Changes between different drafts of DOM Level 3 Events

The DOM Level 3 Events document was previously developed between 2000 and 2003, and and published as a W3C Note, pending further feedback and interest from implementers. In 2006, it was picked up for revision and progress on the Recommendation Track, and is now being revised to reflect the current state of implementation and the needs of script authors.

Despite its status only as a W3C Note, rather than an official Recommendation, DOM 3 Events saw some implementation, and reference by other specifications, so care is being taken to cause minimal disruption, while still adapting the specification to the current environment.

This specification has been reordered significantly from the earlier W3C Note form, and from the structure of DOM2 Events, in order to clarify the material. New diagrams have been put in place to represent hierarchies and events flows more clearly. Here are some of the more important changes between drafts:

Appendix D: Acknowledgements

Many people contributed to the DOM specifications (Level 1, 2 or 3), including participants of the DOM Working Group, the DOM Interest Group,the WebAPI Working Group, and the WebApps Working Group. We especially thank the following:

Andrew Watson (Object Management Group), Andy Heninger (IBM), Angel Diaz (IBM), Arnaud Le Hors (W3C and IBM), Ashok Malhotra (IBM and Microsoft), Ben Chang (Oracle), Bill Smith (Sun), Bill Shea (Merrill Lynch), Bob Sutor (IBM), Chris Lovett (Microsoft), Chris Wilson (Microsoft), David Brownell (Sun), David Ezell (Hewlett-Packard Company), David Singer (IBM), Dimitris Dimitriadis (Improve AB and invited expert), Don Park (invited), Elena Litani (IBM), Eric Vasilik (Microsoft), Gavin Nicol (INSO), Ian Jacobs (W3C), James Clark (invited), James Davidson (Sun), Jared Sorensen (Novell), Jeroen van Rotterdam (X-Hive Corporation), Joe Kesselman (IBM), Joe Lapp (webMethods), Joe Marini (Macromedia), Johnny Stenback (Netscape/AOL), Jon Ferraiolo (Adobe), Jonathan Marsh (Microsoft), Jonathan Robie (Texcel Research and Software AG), Kim Adamson-Sharpe (SoftQuad Software Inc.), Lauren Wood (SoftQuad Software Inc., former Chair), Laurence Cable (Sun), Mark Davis (IBM), Mark Scardina (Oracle), Martin Dürst (W3C), Mary Brady (NIST), Mick Goulish (Software AG), Mike Champion (Arbortext and Software AG), Miles Sabin (Cromwell Media), Patti Lutsky (Arbortext), Paul Grosso (Arbortext), Peter Sharpe (SoftQuad Software Inc.), Phil Karlton (Netscape), Philippe Le Hégaret (W3C, W3C Team Contact and former Chair), Ramesh Lekshmynarayanan (Merrill Lynch), Ray Whitmer (iMall, Excite@Home, and Netscape/AOL, Chair), Rezaur Rahman (Intel), Rich Rollman (Microsoft), Rick Gessner (Netscape), Rick Jelliffe (invited), Rob Relyea (Microsoft), Scott Isaacs (Microsoft), Sharon Adler (INSO), Steve Byrne (JavaSoft), Tim Bray (invited), Tim Yu (Oracle), Tom Pixley (Netscape/AOL), Vidur Apparao (Netscape), Vinod Anupam (Lucent), Anne van Kesteren (Opera Software), Arun Ranganathan (AOL), Björn Höhrmann, Charles McCathieNevile (Opera Software, Co-Chair), Christophe Jolif (ILOG), Dean Jackson (W3C, W3C Team Contact), Doug Schepers (Vectoreal), Gorm Haug Eriksen (Opera Software), Ian Davis (Talis Information Limited), Ian Hickson (Google), John Robinson (AOL), Jonas Sicking (Mozilla Foundation), Luca Mascaro (HTML Writers Guild), Maciej Stachowiak (Apple Computer), Marc Hadley (Sun Microsystems), Michael Shenfield (Research In Motion), Robin Berjon, (Expway, Co-Chair) , Scott Hayman (Research In Motion), Stéphane Sire (IntuiLab), T.V. Raman (Google).

Glossary contributors: Arnaud Le Hors (W3C) and Robert S. Sutor (IBM Research).

Test suite contributors: Fred Drake, Mary Brady (NIST), Carmelo Montanez (NIST), Rick Rivello (NIST), Robert Clary (Netscape), Neil Delima (IBM), with a special mention to Curt Arnold.

In the WebApps Working Group, the following people made substantial material contributions in the process of refining and revising this specification: Hironori Bono (Google), Daniel Danilatos (Google), Travis Leithead (Microsoft), Cameron McCormack (Invited Expert), Olli Pettay (Mozilla), Jacob Rossi (Microsoft), Hallvord R. M. Steen (Opera)

Thanks to all those who have helped to improve this specification by sending suggestions and corrections (Please, keep bugging us with your issues!), or writing informative books or Web sites: Brad Pettit, Dylan Schiemann, David Flanagan, Steven Pemberton, Curt Arnold, Al Gilman, Misha Wolf, Sigurd Lerstad, Michael B. Allen, Alexander J. Vincent, Martin Dürst, Ken Rehor, NAKANO Masayuki, Garrett Smith, Sergey Ilinsky, Martijn Wargers, Sean Hogan, Magnus Kristiansen, Alex Russell, Jorge Chamorro, Peter-Paul Koch, William Edney, Erik Arvidsson, Cameron McCormack, Kazuyuki Ashimura, Øistein E. Andersen, James Su, Tony Chang, Ojan Vafai, Richard Ishida, Paul Irish, Mike Taylor, and Jan Goyvaerts (regular-expressions.info).

D.1 Production Systems

The current drafts of this specification are lovingly hand-crafted in HTML and SVG.

Earlier versions of this specification were written in XML; the HTML, OMG IDL, Java and ECMAScript bindings were all produced automatically. Thanks to Joe English, author of cost, which was used as the basis for producing DOM Level 1. Thanks also to Gavin Nicol, who wrote the scripts which run on top of cost. Arnaud Le Hors and Philippe Le Hégaret maintained the scripts.

After DOM Level 1, we used Xerces as the basis DOM implementation and wish to thank the authors. Philippe Le Hégaret and Arnaud Le Hors wrote the Java programs which are the DOM application.

Thanks also to Jan Kärrman, author of html2ps, which we use in creating the PostScript version of the specification.

Appendix E: References

For the latest version of any W3C specification please consult the list of W3C Technical Reports available at http://www.w3.org/TR.

E.1 Normative References

[CharMod]
Character Model for the World Wide Web 1.0: Fundamentals, M. Dürst, F. Yergeau, R. Ishida, M. Wolf, T. Texin, Editors. World Wide Web Consortium, 15 February 2005. This version of the Character Model for the World Wide Web 1.0: Fundamentals specification is http://www.w3.org/TR/2005/REC-charmod-20050215/. The latest version of Character Model for the World Wide Web 1.0: Fundamentals is available at http://www.w3.org/TR/charmod/.
[DOM3 Core]
Document Object Model Level 3 Core Specification, A. Le Hors, et al., Editors. World Wide Web Consortium, April 2004. This version of the Document Object Model Level 3 Core Specification is http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407. The latest version of DOM Level 3 Core is available at http://www.w3.org/TR/DOM-Level-3-Core.
[DOM2 Events]
Document Object Model Level 2 Events Specification, T. Pixley, Editor. World Wide Web Consortium, November 2000. This version of the Document Object Model Level 2 Events Specification is http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113. The latest version of Document Object Model Level 2 Events is available at http://www.w3.org/TR/DOM-Level-2-Events.
[ECMAScript]
ECMAScript Language Specification, Third Edition. European Computer Manufacturers Association, Standard ECMA-262, December 1999. This version of the ECMAScript Language is available from http://www.ecma-international.org/.
[Java]
The Java Language Specification, J. Gosling, B. Joy, and G. Steele, Authors. Addison-Wesley, September 1996. Available at http://java.sun.com/docs/books/jls
[OMG IDL]
"OMG IDL Syntax and Semantics" defined in The Common Object Request Broker: Architecture and Specification, version 2, Object Management Group. The latest version of CORBA version 2.0 is available at http://www.omg.org/technology/documents/formal/corba_2.htm.
[RFC2119]Key words for use in RFCs to indicate Requirement Levels
S Bradner, 1997. The specification for how to use English to specify normativity, as if it were a technical language. Available at http://rfc.net/rfc2119.html
[Unicode]
The Unicode Standard, Version 5.0, ISBN 0-321-48091-0, as updated periodically by the publication of new versions. See also Versions of the Unicode Standard, available at http://www.unicode.org/unicode/standard/versions, for latest version and additional information on versions of the standard and of the Unicode Character Database.
[UAX #15]
Unicode Normalization Forms, The Unicode Standard Annex #15. The Unicode Consortium, 2006. The latest version of this annex is available at http://www.unicode.org/reports/tr15/.
[XML Namespaces 1.0]
Namespaces in XML 1.0, T. Bray, D. Hollander, A. Layman, and R. Tobin, Editors. World Wide Web Consortium, 16 August 2006. This version of the Namespaces in XML 1.0 Specification is http://www.w3.org/TR/2006/REC-xml-names-20060816. The latest version of Namespaces in XML 1.0 is available at http://www.w3.org/TR/xml-names/.

E.2 Informative References

[ARIA]
Accessible Rich Internet Applications (WAI-ARIA) Version 1.0, M. Cooper, R. Schwerdtfeger, L. Seeman, L. Pappas, eds. World Wide Web Consortium, work in progress, 15 December 2009.
This edition of WAI-ARIA is http://www.w3.org/TR/2009/WD-wai-aria-20091215/.
The latest edition of WAI-ARIA is available at http://www.w3.org/TR/wai-aria/.
[XFORMS]
XForms 1.1, J. Boyer, ed. World Wide Web Consortium, work in progress, 20 October 2009.
This edition of XForms 1.1 is http://www.w3.org/TR/2009/REC-xforms-20091020/.
The latest edition of XForms is available at http://www.w3.org/TR/xforms/.
[CSS2]
Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification, B. Bos, T. Çelik, I. Hickson, H.W. Lie, Editors. World Wide Web Consortium, 08 September 2009, Work in Progress. This version of the CSS 2.1 Specification is http://www.w3.org/TR/2009/CR-CSS2-20090908. The latest version of CSS 2.1 is available at http://www.w3.org/TR/CSS2/.
[DOM3 Load and Save]
Document Object Model Level 3 Load and Save Specification, J. Stenback, A. Heninger, Editors. World Wide Web Consortium, April 2004. This version of the DOM Level 3 Load and Save Specification is http://www.w3.org/TR/2004/REC-DOM-Level-3-LS-20040407. The latest version of DOM Level 3 Load and Save is available at http://www.w3.org/TR/DOM-Level-3-LS.
[DWW95]
Developing International Software for Windows 95 and Windows NT: A Handbook for International Software Design, N. Kano, Author. Microsoft Press, 1995. ISBN 1-55615-840-8.
[HTML 4.01]
HTML 4.01 Specification, D. Raggett, A. Le Hors, and I. Jacobs, Editors. World Wide Web Consortium, December 1999. This version of the HTML 4.01 Recommendation is http://www.w3.org/TR/1999/REC-html401-19991224. The latest version of HTML 4 is available at http://www.w3.org/TR/html4.
[HTML5]
HTML 5, I. Hickson, editor. World Wide Web Consortium, work in progress, 24 June 2010.
This edition of HTML 5 is http://www.w3.org/TR/2010/WD-html5-20100624/.
The latest edition of HTML 5 is available at http://www.w3.org/TR/html5/.
[ISO9995-2/3]
ISO/IEC 9995, Information technology -- Keyboard layouts for text and office systems -- Part 2: Alphanumeric Section and Part 3: Complementary layouts of the alphanumeric zone of the alphanumeric section.
[ISO9995-8]
ISO/IEC 9995-8:2006, Information technology -- Keyboard layouts for text and office systems -- Part 8: Allocation of letters to the keys of a numeric keypad.
[KeyEvent for Java]
Java™ Platform, Standard Edition 6 API Specification, Class java.awt.events.KeyEvent. Sun Microsystems. Available at http://java.sun.com/javase/6/docs/api/java/awt/event/KeyEvent.html.
[Keys enumeration for .Net]
.NET Framework 4.0 Class Library, Keys Enumeration. Microsoft. Available at http://msdn.microsoft.com/en-us/library/system.windows.forms.keys(VS.100,loband).aspx.
[KeyProps]
Legacy Keyboard Event Properties, D. Schepers, editor. World Wide Web Consortium, work in progress, 04 August 2010.
This edition of Legacy Keyboard Event Properties is http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/Note-KeyProps.html.
The latest edition of Legacy Keyboard Event Properties is available at http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/Note-KeyProps.html.
[PCRE]
Perl Compatible Regular Expressions library. Available at http://www.pcre.org/.
[RFC20]ASCII format for Network Interchange
V. Cerf, 1969. Available at http://tools.ietf.org/rfc/rfc20.txt
[US-ASCII]Coded Character Set - 7-Bit American Standard Code for Information Interchange
Standard ANSI X3.4-1986, ANSI, 1986.
[UAAG 2.0]
User Agent Accessibility Guidelines (UAAG) 2.0, J. Allan, K. Ford, J. Richards, J. Spellman, editors. World Wide Web Consortium, work in progress, 8 March 2010. This version of the UAAG 2.0 specfication is http://www.w3.org/WAI/UA/2010/ED-UAAG20-20100308/. The latest version of UAAG 2.0 is available at http://www.w3.org/TR/UAAG20/.
[WIN1252]Windows 1252
S Steele. Unicode, Microsoft, 1998. cp1252 to Unicode table. Available at http://unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT
[XML 1.0]
Extensible Markup Language (XML) 1.0, T. Bray, J. Paoli, C. M. Sperberg-McQueen, et. al, Editors. World Wide Web Consortium, August 2006. This version of the XML 1.0 Recommendation is http://www.w3.org/TR/2006/REC-xml-20060816. The latest version of XML 1.0 is available at http://www.w3.org/TR/xml.