Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.
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].
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 a 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 28 June 2011. The public is encouraged to send comments to the WebApps Working Group's public mailing list for DOM specifications www-dom@w3.org (archive) with subject tag prefix DOM3Events (e.g., [DOM3Events] comment...). 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.
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.
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, 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 Web IDL, but need not support every method or data type defined in Web IDL in order to conform
to DOM3 Events).
This specification defines several classes of conformance for different user agents, specifications, and content authors:
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 with the exception of those marked as deprecated (a conforming user agent
may implement the deprecated interfaces, events, or APIs for backwards compatibility, but is not required to do so in order to be conforming), 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 must support the APIs specified for that event type.
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 can 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.
A conforming browser must also be a conforming implementation of the IDL fragments in this specification, as described in the Web IDL specification. [WEBIDL]
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.
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.
Authoring Note: Content authors are advised to follow best practices as described in accessibility and internationalization guideline specifications.
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.
Specifications or host languages which reference DOM Level 3 Events should not use or recommend features of this specification marked as deprecated, but should use or recommend the indicated replacement for that the feature (if available).
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
'Spacebar'
(e.g., the value of KeyboardEvent.key
); this is the equivalent character
value: '\u0020'
(e.g., the value of KeyboardEvent.char
). This is a glyph that represents that same
character value: ' '
.
Note: This is a note.
Warning! This is a warning. It is used on security notes and to mark deprecated features.
Example: This is an example.
Issue: This is an open issue.
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.
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.
<a>
element is 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
is 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.'\u0020'
) or a glyph representation of the same code point (e.g.,
' '
), and are color coded to help distinguish these two representations.
Note: in source code, some key values, such as non-graphic characters, can be represented using the character escape syntax of the programming language in use.
frozenbefore event listeners on the target object are dispatched, and released or
un-frozenafter this set of of candidate event handlers have been dispatched (allowing these event listeners to add or remove additional listeners on other objects in an event's propagation chain, but not affect the order of listeners that will be invoked on the target object).
Note: Initially capturing the candidate event handlers prevents infinite loops of event listener dispatch on a given target object.
Event.currentTarget
attribute.ö
, é
, â
).Event.preventDefault()
method. For more details, see
Default actions and cancelable events.defaultView
is the document's browsing context's Window Proxy object as defined in HTML5 [HTML5].WheelEvent
interface (such as a mouse wheel or touch pad). The value of a delta (e.g., the deltaX, deltaY, or deltaZ attributes) is to be
interpreted in the context of the current deltaMode
property. The relationship between the physical movement of
a wheel (or other device) and whether the delta is positive or negative is environment and device dependent. However, if a user
agent scrolls as the default action then the sign of the delta is given by a
right-hand coordinate system where positive X,Y, and Z axes are directed towards the right-most edge, bottom-most edge, and farthest depth (away from the user) of the
document, respectively.fire, e.g.,
fire a click
event
or dispatch
a load
event
.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 Level 0refers 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.
DOMString
of length 0
, i.e., a string which contains no characters (neither printing nor control
characters).EventListener
interface and provides an
EventListener.handleEvent()
callback method. Event handlers are language-specific. Event handlers are invoked in the context of a particular object
(the current event target) and are provided with the event object itself.
Note: In JavaScript, user-defined functions are considered to implement the EventListener
interface. Thus the
Event
object will be provided as the first paramter to the user-defined function when it is invoked. Additionally, JavaScript objects can also implement
the EventListener
interface when they define a
method.handleEvent
mousedown
event from the trackpad followed by a mouseup
event from the mouse would not result in a click
event.
Note: there can be interactions between different event orders; for example, a click
event might
be modified by a concurrent keypress
event ('Shift'
+click
); however, the event orders
of these different event sources would be distinct.
'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.target
attribute.click
event
type has different characteristics than the mouseover
or
load
event types. The event type is exposed as 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.wraps aroundfrom the last focus target to the first.
'Enter'
, 'Tab'
, or 'MediaTrackNext'
) associated
with a key in a particular state. Every key has a key value, whether or not it has a character value; this includes
control keys, function keys, modifier keys, dead keys, and any other key.
The key value of any given key at any given time depends upon the key mapping.'Shift'
,
'Alt'
, etc.) and dead key states.
'Shift'
key), or to alter what functionality the key triggers (as with the 'Fn'
or
'Alt'
keys). Refer to the KeyboardEvent.getModifierState()
method for a list of modifier keys defined in this specification. See also Modifier keys.Document
object, root element, and down
to the event target (capture phase), at the
event target itself (target phase), and back up the same chain (bubbling
phase).Event.currentTarget
.
The propagation path is initially composed of one or more event phases as defined by the
event type, but may be interrupted. Also known as an event target chain.ˈ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 and Colemak layouts), most designed for localization or ergonomics.
hit testingfacility is used to determine the target. For specific details regarding hit testing and stacking order, refer to the host language.
\u
followed by a hexadecimal character index in the range 0000
to 10FFFF
, using at least four digits. See also character value.Event.bubbles
or
Event.currentTarget
) before the event has been initialized with Event.initEvent()
. The un-initialized
values of an Event
apply immediately after a new event has been created using the method
DocumentEvent.createEvent()
.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.
Figure 1: graphical representation of an event dispatched in a DOM tree using the DOM event flow
Event objects are dispatched to an event target. At the beginning of the dispatch, implementations must first determine the event object's propagation path.
The propagation path must be an ordered list of current event targets through which the event object must pass. For DOM implementations, the propagation path must reflect the hierarchical tree structure of the document. The last item in the list must be the 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; for DOM implementations, this applies even if an element in the propagation path is moved within the DOM. or removed from the DOM. Additionally, exceptions inside event listeners must not stop the propagation of the event or affect the propagation path.
Example: In the DOM event flow, event listeners might change the position of the 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 must 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 will be skipped, and if Event.stopPropagation()
has been
called prior to the dispatch, all phases must be skipped.
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 must be the next pending event target in the partial propagation path, starting with the first. From the perspective of an event listener this must be the event target the listener has been registered on.
Next, the implementation must determine the current target's candidate event listeners. This must be the list of all event listeners that have been registered on the current target in their order of registration. [HTML5] defines the ordering of listeners registered through event handler attributes. Once determined, the candidate event listeners must not be changed; adding or removing listeners does not affect the current target's candidate event listeners.
Finally, the implementation must process all candidate event handlers in order and trigger each handler if all the following conditions are met:
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.
After an event completes all the phases of its propagation path, its
Event.currentTarget
must be set to null
and the Event.eventPhase
must be
set to 0
(NONE
). All other attributes of the Event
(or interface derived from Event
)
are unchanged (including the Event.target
attribute, which must continue to reference the
event target).
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
must 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 must 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 must 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.
Events are typically dispatched by the implementation as a result of a user action, in response to the completion of a task, or to signal progress during asynchronous
activity (such as a network request). Some events can be used to control the behavior that the implementation may take next (or undo an action that the implementation
already took). Events in this category are said to be cancelable and the behavior they cancel is called their
default action. Cancelable event objects can be associated with one or more default actions.
To cancel an event, call the Event.preventDefault()
method.
Example: A mousedown
event is dispatched immediately after the user presses down a button on a
pointing device (typically a mouse). One possible default action taken by the implementation is to set up a state
machine that allows the user to drag images or select text; the default action depends on what happens next--for
example, if the user's pointing device is over text, a text selection might begin. If the user's pointing device is over an image, then an image-drag action could
begin. Preventing the default action of a mousedown
event prevents these actions from occuring.
Default actions should be performed after the event dispatch has been completed, but in exceptional cases may also be performed immediately before the event is dispatched.
Example: The default action associated with the click
event on <input
type="checkbox"> elements toggles the checked
IDL attribute value of that element. If the click
event's default action is cancelled, then the value is restored to its former state.
When an event is canceled, then the conditional default actions associated with the event must be skipped (or
as mentioned above, if the default actions are carried out before the dispatch, their effect must be undone).
Whether an event object is cancelable must be indicated by the Event.cancelable
attribute.
Event.preventDefault()
stops all related default actions of an event object. The
Event.defaultPrevented
attribute indicates whether an event has already been canceled (e.g., by a prior event listener). If the
DOM application itself initiated the dispatch, then the return value of the EventTarget.dispatchEvent()
method indicates whether the event object was cancelled.
Authoring Note: Many implementations additionally interpret an event listener's return value, such as the value false
, to mean
that the default action of cancelable events will be cancelled (though window.onerror
handlers are cancelled
by returning true
).
Authoring Note: Some cancelable events might not have any observable default actions; for
example, the mousemove
event.
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 with an event object. Other specifications should 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.
Example: As an example, one implementation might scroll a document view by a certain amount as the
default action of a wheel
event, while another implementation might instead zoom the document as its default action.
Events may be dispatched either synchronously or asynchronously.
Events which are synchronous (sync events
) 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 'Del'
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 (async events
) 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: During loading of a document, an inline script element is parsed and executed. The
load
event is queued to be fired asynchronously at the script element. However, because it is an async event, its order with relation to other synchronous
events fired during document load (such as the DOMContentLoaded
event from HTML5) is not guaranteed.
Most events take place in a sequential context. [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].
Authoring Note: Certain events, such as hotkeys
or control keys pressed in a certain sequence, can be
swallowed
by the operating system or the application, interrupting the expected event order.
Events that 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 isTrusted
attribute of trusted events has a
value of true
, while untrusted events have a isTrusted
attribute value of false
.
Most untrusted events should not trigger default actions, with the exception of
click
or DOMActivate
events. These events trigger the
default action of an activation trigger (see Activation triggers and behaviors for more details); these
untrusted events have an isTrusted
attribute value of false
, but still initiate any
default actions for backwards compatibility. All other untrusted events must behave
as if the Event.preventDefault()
method had been called on that event.
Certain 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 attribute
or attribute value.
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's activation of 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 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
has to 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 has to
determine whether to synthesize a DOMActivate
event with the same relevant properties as a
default action of that click
event; appropriate
cues might be whether the click
event is trusted, or whether its event target has a DOMActivate
event listener
registered.
Authoring Note: Don't rely upon the interoperable support of
DOMActivate
in many user agents. Use the click
event type for more accessible behavior instead, due to wider implementation.
Warning! The DOMActivate
event type is deprecated in this specification.
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):
click
DOMActivate
(default action, if supported
by the user agent; synthesized; trusted="false"
)The following is the typical sequence of events when a focused element is activated by a key event (with only pertinent events listed):
keydown
(must be a key which can activate the element, such as the 'Enter'
or 'Spacebar'
key, or the element is not activated)click
(default action; synthesized; trusted="false"
)DOMActivate
(default action, if supported
by the user agent; synthesized; trusted="false"
)This section is informative.
Event operations can throw a DOMException
as specified in their method descriptions.
Note: the exception EventException introduced in DOM Level 2 is
removed in this specification as part of this specification's normative support of Web IDL. EventException formerly defined
an exception code UNSPECIFIED_EVENT_TYPE_ERR
which is replaced in this specification by the use of a DOMException
of type
InvalidStateError
.
The following DOMException
types are used in this specification.
Type | Description |
---|---|
InvalidStateError |
Thrown when the Event.type was not specified by initializing the event before dispatchEvent was
called. Also thrown when the Event object provided to dispatchEvent is already being dispatched. |
NotSupportedError |
Thrown when DocumentEvent.createEvent() is passed an Event
interface that the implementation does not support. |
The interfaces described in this section are fundamental to DOM Level 3 Events and must always be supported by the implementation.
The event types defined in this specification derive from these basic interfaces, and must 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.
Figure 2: graphical representation of the DOM3 Events interface inheritance
The Event
interface provides basic contextual information about an event to all registered event handlers.
Specific events can also implement other derived interfaces, for example the UIEvent
and
MouseEvent
interfaces.
To create an instance of the Event
interface, use the DocumentEvent.createEvent("Event")
method call.
// Introduced in DOM Level 2:
interface Event
{
// PhaseType
const unsigned short NONE = 0;
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(DOMString eventTypeArg,
boolean canBubbleArg,
boolean cancelableArg);
// Introduced in DOM Level 3:
void stopImmediatePropagation();
readonly attribute boolean defaultPrevented;
readonly attribute boolean isTrusted;
};
An integer indicating which phase of the event flow is being processed as defined in Event dispatch and DOM event flow.
NONE
Event
.AT_TARGET
BUBBLING_PHASE
CAPTURING_PHASE
bubbles
of type boolean
, readonlyUsed to indicate whether or not an event is a bubbling event. If the event can bubble the value must be true
, otherwise the value must be
false
.
The un-initialized value of this attribute must be false
.
cancelable
of type boolean
, readonlyUsed 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 must be true
,
otherwise the value must be false
.
The un-initialized value of this attribute must be false
.
Note: Use Event.defaultPrevented
to see whether a cancelable event has beened cancelled or not.
currentTarget
of type EventTarget
,
readonlyUsed to retrieve the current event target whose EventListeners
are currently being processed. This is particularly useful during the capture and bubbling phases.
The un-initialized value of this attribute must be null
.
defaultPrevented
of type boolean
, readonly, introduced in DOM Level 3Used to indicate whether this event has been cancelled or not. Event.defaultPrevented
must return true if both
Event.cancelable
is true
and Event.preventDefault()
has been called for
this event. Otherwise this attribute must return false
.
The un-initialized value of this attribute must be false
.
Note: Calling Event.initEvent()
after an event has been dispatched will reset
the internal default-prevented state of the event.
isTrusted
of type boolean
, readonly, introduced in
DOM Level 3Used to indicate whether this event was generated by the user agent (trusted) or by script (untrusted). See trusted events for more details.
The un-initialized value of this attribute must be false
.
eventPhase
of type unsigned short
, readonlyUsed to indicate the phase of the event's current propagation path (capture, target, or bubble).
The un-initialized value of this attribute must be 0
.
target
of type EventTarget
, readonly
Used to retrieve the event target associated with the Event dispatch and DOM event flow.
The un-initialized value of this attribute must be null
.
timeStamp
of type DOMTimeStamp
, readonlyUsed to specify the time at which the event was created in milliseconds relative to 1970-01-01T00:00:00Z. This value is the un-initialized value of this attribute.
type
of type DOMString
, readonlyThe name of the event type. Specifications that define events, content authors, and authoring tools must use case-sensitive event type names.
The un-initialized value of this attribute must be ""
(the empty string).
initEvent
Initializes attributes of an Event
. The Event
could have been created through the
DocumentEvent.createEvent
method or by the implementation in response to a user action. For any Event
created with the
DocumentEvent.createEvent
method, this method must be called before the Event
is dispatched via the EventTarget.dispatchEvent()
method. If the method is called several
times before invoking EventTarget.dispatchEvent
, only the final invocation takes precedence.
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 must also reset the event object's internal-propagation and default-action-prevention states. This allows an event object to be "reset" before being dispatched multiple times.
Example: If an EventListener
called stopPropagation()
or stopImmediatePropagation()
during
the event's previous dispatch, then after calling this method, the event can be re-dispatched (via dispatchEvent
) and will propagate through all candidate
event listeners along its propagation path (as it did during the prior dispatch). Similarily, if an EventListener
called preventDefault()
during the event's previous dispatch, then after calling this method, the event's defaultPrevented
property will be false
.
Warning! For security reasons, events modified using
Event.initEvent()
must have a isTrusted
attribute value of false
.
See trusted events for more details.
Authoring Note: Trusted events can have their
event type and other attributes changed using this method. However, this method always converts the Event
from a trusted event to an untrusted
event (e.g., the Event.isTrusted
attribute will return false
).
Authoring Note: Trusted events are pre-initialized by the implementation before being dispatched.
As a result, it is not necessary to call Event.initEvent()
prior to re-dispatching the trusted event--however calling
EventTarget.dispatchEvent()
will convert the Event
from a trusted event to an untrusted event (e.g., the
Event.isTrusted
attribute will return false
).
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.
preventDefault
When this method is invoked, 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). Default actions which occur prior to the event's dispatch (see Default actions and cancelable events) are reverted. Calling this method for a non-cancelable event must 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.
stopImmediatePropagation
introduced in DOM Level
3Prevents all other event listeners from being triggered for this event dispatch, including any remaining candiate event listeners. 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.
stopPropagation
Prevents all other event listeners from being triggered, excluding any remaining candiate event listeners. 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.
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.
Authoring Note: Use a prefix string on the event type name for application-specific event types to avoid clashes with future general-purpose event types.
To create an instance of the CustomEvent
interface, use the DocumentEvent.createEvent("CustomEvent")
method call.
Authoring Note: See Appendix A for information about programmatically initializing CustomEvent objects.
// Introduced in DOM Level 3:
interface CustomEvent : Event
{
readonly attribute any detail;
};
detail
of type any
, readonlySpecifies some detail information about the Event
.
The un-initialized value of this attribute must be null
.
The EventTarget
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 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 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
(or removeEventListener
) 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 event listener to be registered more than once and
does not cause a change in the triggering order.
Note: In addition to the EventTarget.addEventListener method, some
host languages allow a content author to register event listeners by the use of attributes, e.g.,
onclick="handleClick()"
(see [HTML5] for further examples). Due to the
language-specific details, this type of event listener registration is not defined in this specification. In general, many event types can be used as an attribute
in this way by adding the prefix on-
to the event type name. Dispatching events to these listeners is expected to behave consistently with the
event registration and propagation defined in this specification, with the same interfaces, properties, and methods.
// Introduced in DOM Level 2:
interface EventTarget
{
// Modified in DOM Level 3:
void addEventListener(DOMString type,
EventListener? listener,
optional boolean useCapture = false);
void removeEventListener(DOMString type,
EventListener? listener,
optional boolean useCapture = false);
boolean dispatchEvent(Event event);
};
addEventListener
Registers an event listener on the EventTarget
. The listener is registered for the capture phase if the
useCapture
parameter is true
, and for the bubble phase otherwise. When the event reaches the target element, listeners for both
the capture and bubble phases are triggered as part of the target phase.
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 must be an object that implements the EventListener
interface or a function.
If listener
is a function then it must be used as the callback for the event; otherwise, if listener
implements
EventListener
, then its handleEvent method must be used as the callback.
useCapture
of type boolean
If true, useCapture
indicates that the user wishes to add the event listener for the capture
and target phases 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.
This parameter must be optional. If not provided, the EventTarget.addEventListener method must behave as if useCapture
were specified to be false
.
Authoring Note: The
useCapture
parameter was manditory in DOM2 Events [DOM2 Events], and omitting this parameter could cause an error
in older implementations.
removeEventListener
Removes an event listener. Calling removeEventListener
with arguments that 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. Implementations
must treat the same listener that was registered twice with both useCapture
true and useCapture
false as independent registrations, and
remove them independently.
Authoring Note: If a listener was registered twice, once for the capture and target phases and once for the target and bubbling phases, this represents two unique registrations. 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.
This parameter must be optional. If not provided, the EventTarget.removeEventListener method must behave as if useCapture
were specified to be false
.
Authoring Note: The useCapture
parameter was manditory in DOM2
Events [DOM2 Events], and omitting this parameter could cause an error in older implementations.
dispatchEvent
modified in DOM Level 3Dispatches an event into the implementation's event model. The event target of the event must be the EventTarget
object on which dispatchEvent
is called.
Warning! For security reasons, events dispatched using
EventTarget.dispatchEvent()
must have a isTrusted
attribute value
of false
. See trusted events for more details.
Parameters
Return Value
|
If after the event object finishes propagating through the DOM event flow its |
Exceptions
Event.type
was not specified by initializing the event before dispatchEvent
was called OR
the Event
object is already being dispatched, a DOMException
of type InvalidStateError
is thrown.The EventListener
interface is the primary way to handle events. EventListener
represents the callback object that the user agent will
invoke when dispatching an Event
to an EventTarget
.
Note: Authors define an object which implements the EventListener
interface and register their event listener using EventTarget.addEventListener. In JavaScript, an EventListener
can be either a function or an object
with a handleEvent
member function.
Note: It is a best practice for authors to 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
[DOM Range], must not copy the event listeners attached to it.
Event listeners can be attached to the newly created Node
afterwards, if so desired.
Moving a Node
, with methods such as Document.adoptNode
, Node.appendChild
, or Range.extractContents
[DOM Range], must not cause the event listeners attached to it to be removed or un-registered.
// Introduced in DOM Level 2:
callback interface EventListener
{
void handleEvent(Event event);
};
The DocumentEvent
interface provides a mechanism by which the user can create an Event
object of a type supported
by the implementation. The DocumentEvent
interface must be implemented on the same object that implements the Document
interface.
// Introduced in DOM Level 2:
[NoInterfaceObject]
interface DocumentEvent
{
// Modified in DOM Level 3:
Event createEvent(DOMString eventInterface);
};
Document implements DocumentEvent;
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.
Note: After calling createEvent
, and prior to dispatching the event with the
EventTarget.dispatchEvent()
method, the
Event
will need to be initialized with the appropriate event initialization
method (e.g., initEvent
, initMouseEvent
, etc.) in order to associate it with an event type and related 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, the following case-insensitive feature names are valid values for the parameter eventInterface
:
Legacy feature name | Resulting event interface |
---|---|
"Events" |
Event |
"HTMLEvents" |
Event |
"UIEvents" |
UIEvent |
"MouseEvents" |
MouseEvent |
"MutationEvents" |
MutationEvent |
Warning! For security reasons, events generated using
DocumentEvent.createEvent("Event")
must have a isTrusted
attribute
value of false
. See trusted events for more details.
Return Value
Event |
The newly created event object. |
Exceptions
Event
interface requested, a DOMException
of type NotSupportedError
is thrown.Each event must 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
.
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 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 an informative summary of the event types defined in this specification.
Event Type | Sync / Async | Bubbling phase | Trusted 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 | Show a text composition system candidate window |
compositionupdate |
Sync | Yes | Element |
CompositionEvent |
No | none |
compositionend |
Sync | Yes | Element |
CompositionEvent |
No | none |
dblclick |
Sync | Yes | Element |
MouseEvent |
No | none |
DOMActivate
Warning! Deprecated |
Sync | Yes | Element |
UIEvent |
Yes | none |
DOMAttrModified
Warning! Deprecated |
Sync | Yes | Element |
MutationEvent |
No | none |
DOMCharacterDataModified
Warning! Deprecated |
Sync | Yes | Text , Comment , CDATASection , ProcessingInstruction |
MutationEvent |
No | none |
DOMFocusIn
Warning! Deprecated |
Sync | Yes | Element |
FocusEvent |
No | none |
DOMFocusOut
Warning! Deprecated |
Sync | Yes | Element |
FocusEvent |
No | none |
DOMNodeInserted
Warning! Deprecated |
Sync | Yes | Element , Attr , Text , Comment , CDATASection , DocumentType , EntityReference ,
ProcessingInstruction |
MutationEvent |
No | none |
DOMNodeInsertedIntoDocument
Warning! Deprecated |
Sync | No | Element , Attr , Text , Comment , CDATASection , DocumentType , EntityReference ,
ProcessingInstruction |
MutationEvent |
No | none |
DOMNodeRemoved
Warning! Deprecated |
Sync | Yes | Element , Attr , Text , Comment , CDATASection , DocumentType , EntityReference ,
ProcessingInstruction |
MutationEvent |
No | none |
DOMNodeRemovedFromDocument
Warning! Deprecated |
Sync | No | Element , Attr , Text , Comment , CDATASection , DocumentType , EntityReference ,
ProcessingInstruction |
MutationEvent |
No | none |
DOMSubtreeModified
Warning! Deprecated |
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 | Document , Element |
KeyboardEvent |
Yes | Varies: keypress event; launch text composition
system; blur and focus events;
DOMActivate event; other event |
keypress |
Sync | Yes | Document , Element |
KeyboardEvent |
Yes | Varies: launch text composition system; blur
and focus events; DOMActivate
event; other event |
keyup |
Sync | Yes | Document , Element |
KeyboardEvent |
Yes | none |
load |
Async | No | defaultView , Document , Element |
Event |
No | none |
mousedown |
Sync | Yes | Element |
MouseEvent |
Yes | Varies: start a drag/drop operation; start a text selection; start a scroll/pan interaction (in combination with the middle mouse button, if supported) |
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 | Invoke a context menu (in combination with the right mouse button, if supported) |
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 |
unload |
Sync | No | defaultView , Document , Element |
Event |
No | none |
wheel |
Async | Yes | defaultView , Document , Element |
WheelEvent |
Yes | Scroll (or zoom) the document |
Example: The following is one way to interpret the above table: the load
event will
trigger event listeners attached on Element
nodes for that event and on the capture and target phases. This event is not cancelable. 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 would not be triggered.
Note: Don't interpret the above table as definitive for the listed event types. For example, the load
event is used in other
specifications, for example, in XMLHttpRequest. Similarly, dispatchEvent
can be used to dispatch untrusted events to
listeners on any object that also implements EventTarget
.
Note: The event objects associated with the event types described above contain additional context information--refer to the description of the DOM interfaces for further information.
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 in the future. 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.
The User Interface event module contains basic event types associated with user interfaces and document manipulation.
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.
// Introduced in DOM Level 2:
interface UIEvent : Event
{
readonly attribute AbstractView? view;
readonly attribute long detail;
// Deprecated in DOM Level 3:
void initUIEvent(DOMString typeArg,
boolean canBubbleArg,
boolean cancelableArg,
AbstractView? viewArg,
long detailArg);
};
detail
of type long
, readonlySpecifies some detail information about the Event
, depending on the type of event.
The un-initialized value of this attribute must be 0
.
view
of type AbstractView
, readonlyThe view
attribute identifies the AbstractView
from which the event was generated.
The un-initialized value of this attribute must be null
.
initUIEvent
Initializes attributes of an UIEvent
object. This method has the same behavior as Event.initEvent()
.
Warning! The initUIEvent
method is deprecated, but supported for backwards-compatibility with widely-deployed
implementations. See Appendix A for a suggested (informative-only) alternate initializer syntax.
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 AbstractView
Specifies UIEvent.view
. This value may be null
.
detailArg
of type long
Specifies UIEvent.detail
.
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
Type | DOMActivate |
---|---|
Interface | UIEvent |
Sync / Async | Sync |
Bubbles | Yes |
Target | Element |
Cancelable | Yes |
Default action | none |
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.
load
Type | load |
---|---|
Interface | UIEvent if generated from a user interface, Event otherwise. |
Sync / Async | Async |
Bubbles | No |
Target | defaultView , Document , Element |
Cancelable | No |
Default action | none |
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.
Note: for legacy reasons, load
events for resources inside
the document (e.g., images) do not include the defaultView in the propagation path in HTML implementations. See
[HTML5] for more information.
unload
Type | unload |
---|---|
Interface | UIEvent if generated from a user interface, Event otherwise. |
Sync / Async | Sync |
Bubbles | No |
Target | defaultView , Document , Element |
Cancelable | No |
Default action | none |
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 must 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
Type | abort |
---|---|
Interface | UIEvent if generated from a user interface, Event otherwise. |
Sync / Async | Sync |
Bubbles | No |
Target | Element |
Cancelable | No |
Default action | none |
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
Type | error |
---|---|
Interface | UIEvent if generated from a user interface, Event otherwise. |
Sync / Async | Async |
Bubbles | No |
Target | Element |
Cancelable | No |
Default action | none |
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
Type | select |
---|---|
Interface | UIEvent if generated from a user interface, Event otherwise. |
Sync / Async | Sync |
Bubbles | Yes |
Target | Element |
Cancelable | No |
Default action | none |
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 will use native capabilities of the host languages, such as the Document.getSelection()
method of the
HTML Editing APIs [HTML Editing].
Note: The select
event might not be available
for all elements in all languages. For example, in [HTML5],
select
events can be dispatched only on form input
and textarea
elements. Implementations can 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
Type | resize |
---|---|
Interface | UIEvent |
Sync / Async | Sync |
Bubbles | No |
Target | defaultView |
Cancelable | No |
Default action | none |
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.
User agents which support continuous reflow of the document's layout during user-initiated resizing must dispatch this event synchronously after each reflow of the document.
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: The resize
event is distinct from the
SVG zoom
event types, though both can occur at the same time, or as the consequence of the same user action. In particular, browser
font zooming
or page zooming
will 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
Type | scroll |
---|---|
Interface | UIEvent |
Sync / Async | Async |
Bubbles | No / Yes |
Target | defaultView , Document , Element |
Cancelable | No |
Default action | none |
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.
When dispatched on the Document
element, this event type must bubble to the
defaultView
object.
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.
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.
Authoring Note: See Appendix A for information about programmatically initializing FocusEvent objects.
// Introduced in DOM Level 3:
interface FocusEvent : UIEvent
{
readonly attribute EventTarget? relatedTarget;
};
relatedTarget
of type EventTarget
,
readonlyUsed 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
.
The un-initialized value of this attribute must be null
.
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):
focusin
(before first target element receives focus)focus
(after first target element receives focus)DOMFocusIn
(if supported)focusout
(before first target element loses focus)focusin
(before second target element receives focus)blur
(after first target element loses focus)DOMFocusOut
(if supported)focus
(after second target element receives focus)DOMFocusIn
(if supported)Note: This specification does not define the behavior of focus events when interacting with methods such as focus()
or
blur()
; see the relevant specifications where those methods are defined for such behavior.
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 might be on one of many different applications, one of which is the browser; when the browser has focus, the user can 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 in 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 might receive focus, the conditions under 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 might be given focus by moving a pointer over it, while other circumstances might require a mouse click; some elements might not be focusable at all, and some might 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.
The Focus event types are listed below.
blur
Type | blur |
---|---|
Interface | FocusEvent |
Sync / Async | Sync |
Bubbles | No |
Target | Element |
Cancelable | No |
Default action | none |
Context info |
|
A user agent must dispatch this event when an event target loses
focus. The focus must 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
Type | DOMFocusIn |
---|---|
Interface | FocusEvent |
Sync / Async | Sync |
Bubbles | Yes |
Target | Element |
Cancelable | No |
Default action | none |
Context info |
|
A user agent must dispatch this event when an event target receives
focus. The focus must be given to the element before the dispatch of this event type. This event type must 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
Type | DOMFocusOut |
---|---|
Interface | FocusEvent |
Sync / Async | Sync |
Bubbles | Yes |
Target | Element |
Cancelable | No |
Default action | none |
Context info |
|
A user agent must dispatch this event when an event target loses
focus. The focus must be taken from the element before the dispatch of this event type. This event type must 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
Type | focus |
---|---|
Interface | FocusEvent |
Sync / Async | Sync |
Bubbles | No |
Target | Element |
Cancelable | No |
Default action | none |
Context info |
|
A user agent must dispatch this event when an event target receives
focus. The focus must 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
Type | focusin |
---|---|
Interface | FocusEvent |
Sync / Async | Sync |
Bubbles | Yes |
Target | Element |
Cancelable | No |
Default action | none |
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 can 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 access to both the element losing focus and the element gaining focus
without the use of the blur
or focusout event
types.
focusout
Type | focusout |
---|---|
Interface | FocusEvent |
Sync / Async | Sync |
Bubbles | Yes |
Target | Element |
Cancelable | No |
Default action | none |
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.
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.
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.
Note: Ancestors of the targeted element can use event bubbling to obtain notifications 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
, implementations can 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
).
// 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;
// Deprecated in DOM Level 3:
void initMouseEvent(DOMString typeArg,
boolean canBubbleArg,
boolean cancelableArg,
AbstractView? viewArg,
long detailArg,
long screenXArg,
long screenYArg,
long clientXArg,
long clientYArg,
boolean ctrlKeyArg,
boolean altKeyArg,
boolean shiftKeyArg,
boolean metaKeyArg,
unsigned short buttonArg,
EventTarget? relatedTargetArg);
// Introduced in DOM Level 3:
boolean getModifierState(DOMString keyArg);
};
altKey
of type boolean
, readonlyRefer to the KeyboardEvent.altKey
attribute.
button
of type unsigned short
, readonlybutton
must 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) or the un-initialized value.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 provide or simulate more buttons, and values higher than 2
may be used to represent such buttons.
Note: The value of button
is not updated for events not caused by the depression/release of a mouse button. In these
scenarios, take care not to interpret the value 0
as the left button, but rather as the un-initialized
value
Authoring Note: Some default actions related to events such as
mousedown
and mouseup
depend on the specific mouse button in use.
The un-initialized value of this attribute must be 0
.
buttons
of type unsigned short
, readonlyDuring any mouse events, buttons
must be used to indicate which combination of mouse buttons are
currently being pressed, expressed as a bitmask.
Note: Though similarly named, the values for the buttons
attribute and the button
attribute are very different. The value of button
is assumed to be valid during mousedown
/
mouseup
event handlers, whereas the buttons
attribute reflects the state of the mouse's buttons for any
trusted MouseEvent
object (while it is being dispatched), because it can represent the "no button currently active" state (0).
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 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
, ... ).
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.
Authoring Note: Some default actions related to events such as
mousedown
and mouseup
depend on the specific mouse button in use.
The un-initialized value of this attribute must be 0
.
clientX
of type long
, readonlyThe horizontal coordinate at which the event occurred relative to the viewport associated with the event.
The un-initialized value of this attribute must be 0
.
clientY
of type long
, readonlyThe vertical coordinate at which the event occurred relative to the viewport associated with the event.
The un-initialized value of this attribute must be 0
.
ctrlKey
of type boolean
, readonlyRefer to the KeyboardEvent.ctrlKey
attribute.
The un-initialized value of this attribute must be false
.
metaKey
of type boolean
, readonlyRefer to the KeyboardEvent.metaKey
attribute.
The un-initialized value of this attribute must be false
.
relatedTarget
of type EventTarget
,
readonlyUsed to identify a secondary EventTarget
related to a UI event, depending on the type of event.
The un-initialized value of this attribute must be null
.
screenX
of type long
, readonlyThe horizontal coordinate at which the event occurred relative to the origin of the screen coordinate system.
The un-initialized value of this attribute must be 0
.
screenY
of type long
, readonlyThe vertical coordinate at which the event occurred relative to the origin of the screen coordinate system.
The un-initialized value of this attribute must be 0
.
shiftKey
of type boolean
, readonlyRefer to the KeyboardEvent.shiftKey
attribute.
getModifierState
introduced in DOM Level 3Queries 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. |
initMouseEvent
Initializes attributes of a MouseEvent
object. This method has the same behavior as UIEvent.initUIEvent()
.
Warning! The initMouseEvent
method is deprecated, but supported for backwards-compatibility with widely-deployed
implementations. See Appendix A for a suggested (informative-only) alternate initializer syntax.
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 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
.
Implementations must maintain the current click count when generating mouse events. This must be a non-negative integer indicating the number of consecutive clicks of a pointing device button within a specific time. The delay after which the count resets is specific to the environment configuration.
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:
mousemove
mouseover
mouseenter
mousemove
(multiple events)mouseout
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:
mousedown
mousemove
(optional, multiple events, some limits)mouseup
click
mousemove
(optional, multiple events, some limits)mousedown
mousemove
(optional, multiple events, some limits)mouseup
click
dblclick
Note: 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 will be implementation-, device-, and platform-specific. This tolerance can aid users that have physical
disabilities like unsteady hands when these users interact with a pointing device.
Each implementation will 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 fire click
and
dblclick
events on the nearest common ancestor when the event targets of the associated
mousedown
and mouseup
events are different.
If the event target (e.g. the target element) is removed from the DOM during the mouse events sequence, the remaining events of the sequence must not be fired on that element.
Example: if the target element is removed from the DOM as the result of a
mousedown
event, no events for that element will be dispatched for mouseup
,
click
, or dblclick
, nor any default
activation events; however, the mouseup
event will still be dispatched on the element that is exposed
to the mouse after the removal of the initial target element. Similarly, if the target element is removed from the DOM during the dispatch of a mouseup
event, the click
and subsequent events will
not be dispatched.
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.
click
Type | click |
---|---|
Interface | MouseEvent |
Sync / Async | Sync |
Bubbles | Yes |
Target | Element |
Cancelable | Yes |
Default action | Varies |
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 depends 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 will likely 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 are encouraged to 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 can be considered a device-independent event type for element activation.
The default action of the click
event type varies
based on the 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:
MouseEvent.button
value is 0
,
MouseEvent.buttons
value is 1
):
MouseEvent.button
value is 1
,
MouseEvent.buttons
value is 2
):
MouseEvent.button
value is 2
,
MouseEvent.buttons
value is 4
):
dblclick
Type | dblclick |
---|---|
Interface | MouseEvent |
Sync / Async | Sync |
Bubbles | Yes |
Target | Element |
Cancelable | Yes |
Default action | none |
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 does 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 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:
MouseEvent.button
value is 0
,
MouseEvent.buttons
value is 1
):
mousedown
Type | mousedown |
---|---|
Interface | MouseEvent |
Sync / Async | Sync |
Bubbles | Yes |
Target | Element |
Cancelable | Yes |
Default action | Varies: Start a drag/drop operation; start a text selection; start a scroll/pan interaction (in combination with the middle mouse button, if supported) |
Context info |
|
A user agent must dispatch this event when a pointing device button is pressed over an element.
Note: Many implementations use the mousedown
event to begin a variety of contextually dependent default actions. These default actions can be prevented if this event is canceled. Some of these default actions could include: beginning
a drag/drop interaction with an image or link; starting text selection; etc. Additionally, some implementations provide a mouse-driven panning feature that is activated when
the middle mouse button is pressed at the time the mousedown
event is dispatched.
mouseenter
Type | mouseenter |
---|---|
Interface | MouseEvent |
Sync / Async | Sync |
Bubbles | No |
Target | Element |
Cancelable | No |
Default action | none |
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.1]. See also the
mouseleave
event type.
mouseleave
Type | mouseleave |
---|---|
Interface | MouseEvent |
Sync / Async | Sync |
Bubbles | No |
Target | Element |
Cancelable | No |
Default action | none |
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.1]. See also the
mouseenter
event type.
mousemove
Type | mousemove |
---|---|
Interface | MouseEvent |
Sync / Async | Sync |
Bubbles | Yes |
Target | Element |
Cancelable | Yes |
Default action | none |
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 is 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.
Authoring Note: In some implementation environments, such as a browser, mousemove
events can continue
to fire if the user began a drag operation (e.g., a mouse button is pressed) and the pointing device has left the boundary of the user agent.
mouseout
Type | mouseout |
---|---|
Interface | MouseEvent |
Sync / Async | Sync |
Bubbles | Yes |
Target | Element |
Cancelable | Yes |
Default action | none |
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
Type | mouseover |
---|---|
Interface | MouseEvent |
Sync / Async | Sync |
Bubbles | Yes |
Target | Element |
Cancelable | Yes |
Default action | none |
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 it bubbles, 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
Type | mouseup |
---|---|
Interface | MouseEvent |
Sync / Async | Sync |
Bubbles | Yes |
Target | Element |
Cancelable | Yes |
Default action | Invoke a context menu (in combination with the right mouse button, if supported) |
Context info |
|
A user agent must dispatch this event when a pointing device button is released over an element.
Note: Many implementations will invoke a context menu as the default action of this event if the right mouse button is being released.
Authoring Note: In some implementation environments, such as a browser, a mouseup
event
can be dispatched even if the pointing device has left the boundary of the user agent, e.g., if the user began a drag operation with a mouse button pressed).
Wheels are devices that can be rotated in one or more spatial dimensions, and which can be associated with a pointer device. The coordinate system depends on the environment configuration.
Example: The user's environment might 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 deltaZ attributes of WheelEvent
objects indicate a measurement along their respective axes
in units of pixels, lines, or pages. The reported measurements are provided after an environment-specific algorithm translates the actual rotation/movement of
the wheel device into the appropriate values and units.
Authoring Note: A user's environment settings can be customized to interpret actual rotation/movement of a wheel device in different ways.
One movement of a common dented
mouse wheel can produce a measurement of 162 pixels (162 is just an example value, actual values can depend on the current screen
dimensions of the user-agent). But a user can change their default environment settings to speed-up their mouse wheel, increasing this number. Furthermore, some
mouse wheel software can support acceleration (the faster the wheel is rotated/moved, the greater the delta of each measurement) or even sub-pixel rotation measurements.
Because of this, authors can not assume a given rotation amount in one user agent will produce the same delta value in all user agents.
The sign (positive or negative) of the values of the deltaX, deltaY, and deltaZ attributes must be consistent between multiple dispatches of the
wheel
event while the motion of the actual wheel device is rotating/moving in the same direction. If a user agent scrolls as the
default action of the wheel
event then the sign of the delta should be given by a right-hand coordinate system where positive X,
Y, and Z axes are directed towards the right-most edge, bottom-most edge, and farthest depth (away from the user) of the document, respectively.
Note: Individual user agents can (depending on their environment and hardware configuration) interpret the same physical user interaction on the wheel differently. For example, a vertical swipe on the edge of a trackpad from top to bottom can be interpreted as a wheel action intended to either scroll the page down or to pan the page up (i.e., resulting in either a positive or negative deltaY value respectively).
The WheelEvent
interface provides specific contextual information associated with wheel
events.
To create an instance of the WheelEvent
interface, use the DocumentEvent.createEvent("WheelEvent")
method call.
Authoring Note: See Appendix A for information about programmatically initializing WheelEvent objects.
// 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 float deltaX;
readonly attribute float deltaY;
readonly attribute float deltaZ;
readonly attribute unsigned long deltaMode;
};
This set of constants must be used to indicate the units of measurement for the delta
values. The precise measurement
is specific to device, operating system, and application configurations.
DOM_DELTA_PIXEL
delta
must be pixels. This is the most typical case in most operating system and implementation
configurations.DOM_DELTA_LINE
delta
must be individual lines of text. This is the case for many form controls.DOM_DELTA_PAGE
delta
must be pages, either defined as a single screen or as a demarcated page.deltaX
of type float
, readonlyIn user agents where the default action of the wheel
event is to scroll, the value must be the measurement along
the x-axis (in pixels, lines, or pages) to be scrolled in the case where the event is not cancelled. Otherwise, this is an implementation-specific
measurement (in pixels, lines, or pages) of the movement of a wheel device around the x-axis.
The un-initialized value of this attribute must be 0
.
deltaY
of type float
, readonlyIn user agents where the default action of the wheel
event is to scroll, the value must be the measurement along
the y-axis (in pixels, lines, or pages) to be scrolled in the case where the event is not cancelled. Otherwise, this is an implementation-specific
measurement (in pixels, lines, or pages) of the movement of a wheel device around the y-axis.
The un-initialized value of this attribute must be 0
.
deltaZ
of type float
, readonlyIn user agents where the default action of the wheel
event is to scroll, the value must be the measurement along
the z-axis (in pixels, lines, or pages) to be scrolled in the case where the event is not cancelled. Otherwise, this is an implementation-specific
measurement (in pixels, lines, or pages) of the movement of a wheel device around the z-axis.
The un-initialized value of this attribute must be 0
.
deltaMode
of type unsigned long
, readonlyThe deltaMode
attribute contains an indication of the units of measurement for the delta
values.
The default value is DOM_DELTA_PIXEL
(pixels).
The un-initialized value of this attribute must be 0
.
The Wheel event types are listed below.
wheel
Type | wheel |
---|---|
Interface | WheelEvent |
Sync / Async | Async |
Bubbles | Yes |
Target | defaultView , Document , Element |
Cancelable | Yes |
Default action | scroll (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. Depending on the platform and input device, diagonal wheel
deltas may be delivered either as a single wheel
event with multiple non-zero axes or as separate wheel
events for each non-zero axis.
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).
Note: In some user agents, or with some input devices, the speed that the wheel has been
turned can affect the delta
values, with a faster speed producing a higher delta
value.
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. Refer to Keyboard events and key values for more details, including examples on how Keyboard Events are used in combination with Composition Events. Depending on the character generation device, keyboard events might not be generated.
Authoring Note: Keyboard events are only one modality of providing textual input. For editing scenarios, consider also using the "input" event defined in [HTML5] as an alternate to (or in addition to) keyboard events.
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.
Authoring Note: See Appendix A for information about programmatically initializing KeyboardEvent objects.
// 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 location;
readonly attribute boolean ctrlKey;
readonly attribute boolean shiftKey;
readonly attribute boolean altKey;
readonly attribute boolean metaKey;
readonly attribute boolean repeat;
readonly attribute DOMString locale;
boolean getModifierState(DOMString keyArg);
};
This set of constants must 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.
DOM_KEY_LOCATION_STANDARD
The key activation must 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_LEFT
The key activated originated from 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_RIGHT
The key activation originated from 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_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_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.
altKey
of type boolean
, readonlytrue
if the 'Alt'
(alternative) or Option
key modifier was active.
The un-initialized value of this attribute must be false
.
ctrlKey
of type boolean
, readonlytrue
if the 'Control'
(control) key modifier was active.
The un-initialized value of this attribute must be false
.
char
of type DOMString
, readonlychar
holds the character value of the key pressed. If the key press has a printed representation, then the value must be a non-empty 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 the empty string.
Note: the char
attribute is not related to the legacy charCode
attribute and does
not have the same set of values.
The un-initialized value of this attribute must be ""
(the empty string).
key
of type DOMString
, readonlykey
holds the key value of the key pressed. If the value is has a printed representation, 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 keyCode
attribute and does not have the same set of values.
The un-initialized value of this attribute must be ""
(the empty string).
location
of type unsigned long
, readonlyThe location
attribute contains an indication of the location of the key on the device, as described in
Keyboard event types.
The un-initialized value of this attribute must be 0
.
metaKey
of type boolean
, readonlytrue
if the meta (Meta) key modifier was active.
Note: The 'Command'
key modifier on Macintosh systems is represented using this key modifier.
The un-initialized value of this attribute must be false
.
shiftKey
of type boolean
, readonlytrue
if the shift (Shift) key modifier was active.
The un-initialized value of this attribute must be false
.
repeat
of type boolean
, readonlytrue
if the key has been pressed in a sustained manner. Holding down a key must result in the repeating the events
keydown
, keypress
(when supported by the user agent) in this order, at a rate determined by the system configuration. For mobile devices which have long-key-press
behavior, the first key event with a repeat attribute value of 'true'
must 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.
The un-initialized value of this attribute must be false
.
locale
of type DOMString
, readonlyThe locale
DOMString
attribute contains a BCP-47 tag [BCP-47] indicating the locale for which the keyboard originating
the event is configured, e.g. "en-US"
. The locale
may be the empty string when inapplicable
or unknown, e.g. when this information is not exposed by the underlying platform.
Note: locale
does not necessarily indicate the locale of the data or the context in which
it is being entered. For example, a French user often might not switch to an English keyboard setting when typing English, in which case the locale
will still indicate French. Nor can it be used to definitively calculate the physical
or virtual
key associated with the event, or the character
printed on that key.
The un-initialized value of this attribute must be ""
(the empty string).
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'
'ScrollLock'
'Shift'
'SymbolLock'
, and
'OS'
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. |
Warning! Legacy keyboard event implementations include three additional attributes, keyCode
, charCode
, and
which
. 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 might 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 can use KeyboardEvent.key
or KeyboardEvent.char
instead, in conforming DOM Level 3 Events implementations. For more information, see
the informative appendix on Legacy key attributes: keyCode, charCode, and which.
Note: For compatibility with existing content, virtual keyboards, such as software keyboards on screen-based input devices, are expected to produce the normal range of keyboard events, even though they do not possess physical keys.
Note: In some implementations or system configurations, some key events, or their values, might be suppressed by the IME in use.
The keyboard events defined in this specification occur in a set order relative to one another, for any given key:
keydown
keypress
(only for keys which produce a character
value)keydown
(with repeat attribute set to
true
)keypress
(with repeat attribute set to
true
; only for keys which produce a character value)keyup
Note: Typically, any default actions associated with any particular
key are completed before the keyup
event is dispatched; this might delay the keyup
event slightly (though this is not likely to be a perceptible delay).
The event 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 might 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.
The keyboard event types are listed below.
keydown
Type | keydown |
---|---|
Interface | KeyboardEvent |
Sync / Async | Sync |
Bubbles | Yes |
Target | Document , Element |
Cancelable | Yes |
Default action | Varies: keypress 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 must be generated after the key mapping. This event type must be dispatched before the keypress
and keyup
events event associated with the
same key.
The default action of the keydown
event depends upon the key:
keypress
event; in the case where the key which is associated with multiple characters (such as with a macro or certain sequences of dead keys), the default action must
be to dispatch one keypress
event for each character'Tab'
key, the default action must be to shift the document focus from the currently focused
element (if any) to the new focused element, as described in Focus Event Types'Enter'
or 'Space'
key and the
current focus is on a state-changing element, the default action must 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
Type | keypress |
---|---|
Interface | KeyboardEvent |
Sync / Async | Sync |
Bubbles | Yes |
Target | Document , Element |
Cancelable | Yes |
Default action | Varies: 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 keypress
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 must be generated after the key mapping. It must not be fired when using an input method editor. 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 might 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. When
in editing contexts, authors can subscribe to the "input" event defined in [HTML5] instead.
keyup
Type | keyup |
---|---|
Interface | KeyboardEvent |
Sync / Async | Sync |
Bubbles | Yes |
Target | Document , Element |
Cancelable | Yes |
Default action | none |
Context info |
|
A user agent must dispatch this event when a key is released. The
keyup
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 must be generated after the key mapping. This event type must be dispatched after the keydown
and keypress
events event associated with
the same key.
Note: the keydown
and
keyup
events are traditionally associated with detecting any key, not just those which produce a character
value.
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 might not be commonly available on keyboard. For example, Composition events might 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.
Note: While a composition session is active, keyboard events can be dispatched to the DOM if the keyboard is the input device used
with the composition session. See the compositionstart
event details and IME section
for relevent event ordering.
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
) might not be available through this interface, in which case the selection may be represented by the
empty string.
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.
Authoring Note: See Appendix A for information about programmatically initializing CompositionEvent objects.
// Introduced in DOM Level 3:
interface CompositionEvent : UIEvent
{
readonly attribute DOMString? data;
readonly attribute DOMString locale;
};
data
of type DOMString
, readonlydata
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.
The un-initialized value of this attribute must be ""
(the empty string).
locale
of type DOMString
, readonlyThe locale
DOMString
attribute contains a BCP-47 tag [BCP-47] indicating the locale for which the IME originating
the event is configured, e.g. "ja"
, "zh-Hans"
, "ko"
. May be the empty string
when inapplicable or unknown, e.g. when this information is not exposed by the underlying platform or application.
Note: locale
does not necessarily indicate the locale of the data or the context in
which it is being entered. For example, a French user often might not switch to an English keyboard setting when typing English, in which case the locale
will still indicate French, even though the data is actually English. Similarly, an IME application could fail to distinguish between the locale of Chinese and
Kanji characters.
The un-initialized value of this attribute must be ""
(the empty string).
The composition events defined in this specification occur in a set order relative to one another:
compositionstart
compositionupdate
(multiple events)compositionend
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.
compositionstart
: ''
compositionupdate
: 'test'
compositionupdate
: 'text'
compositionend
: 'text'
The composition event types are listed below.
compositionstart
Type | compositionstart |
---|---|
Interface | CompositionEvent |
Sync / Async | Sync |
Bubbles | Yes |
Target | Element |
Cancelable | Yes |
Default action | Start a new composition session when a text composition system is enabled |
Context info |
|
A user agent must dispatch this event when a text composition
system is enabled and a new composition session is about to begin (or has begun, depending on the text composition
system) 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 must be the empty string.
This event must be dispatched immediately before a text composition system begins a new composition session, and before the DOM is modified due to the composition process. The default action of this event is for the text composition system to start a new composition session. If this event is canceled, the text composition system should discard the current composition session.
Note: Canceling the compositionstart
event type is distinct
from canceling the text composition system itself (e.g., by hitting a cancel button or closing an IME window).
Note: Some IMEs do not support cancelling an in-progress composition session (e.g., such as GTK which doesn't presently have such an API). In these
cases, calling preventDefault
will not stop this event's default action.
compositionupdate
Type | compositionupdate |
---|---|
Interface | CompositionEvent |
Sync / Async | Sync |
Bubbles | Yes |
Target | Element |
Cancelable | No |
Default action | none |
Context info |
|
A user agent should dispatch this event during a composition session when a
text composition system updates its active text passage with a new character, which is added to the string in CompositionEvent.data
.
Some text composition systems might 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 the empty string.
compositionend
Type | compositionend |
---|---|
Interface | CompositionEvent |
Sync / Async | Sync |
Bubbles | Yes |
Target | Element |
Cancelable | No |
Default action | none |
Context info |
|
A user agent must dispatch this event when a text composition system completes or cancels the current composition session.
This event is dispatched immediately after the text composition system completes the composition session (e.g., the IME is closed, minimized, switched out of focus, or otherwise dismissed, and the focus switched back to the user agent).
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.
Note: none of the event types associated with the MutationEvent
interface 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. DOM4 [DOM4] provides a new mechanism using a MutationObserver
interface which
addresses the use cases that mutation events solve, but in a more performant manner. Thus, this specification describes mutation events for reference and completeness of legacy
behavior, but deprecates the use of the MutationEvent
interface.
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.
// Deprecated in DOM Level 3:
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(DOMString typeArg,
boolean canBubbleArg,
boolean cancelableArg,
Node? relatedNodeArg,
DOMString prevValueArg,
DOMString newValueArg,
DOMString attrNameArg,
unsigned short attrChangeArg);
};
An integer indicating in which way the Attr
was changed.
ADDITION
Attr
was just added.MODIFICATION
Attr
was modified in place.REMOVAL
Attr
was just removed.attrChange
of type unsigned short
, readonlyattrChange
indicates the type of change which triggered the DOMAttrModified
event. The values can be MODIFICATION
, ADDITION
, or REMOVAL
.
The un-initialized value of this attribute must be 0
.
Warning: There is no defined constant for the attrChange value of 0 (the un-initialized value).
attrName
of type DOMString
, readonlyattrName
indicates the name of the changed Attr
node in a DOMAttrModified
event.
The un-initialized value of this attribute must be ""
(the empty string).
newValue
of type DOMString
, readonlynewValue
indicates the new value of the Attr
node in DOMAttrModified
events, and of the CharacterData
node in DOMCharacterDataModified
events.
The un-initialized value of this attribute must be ""
(the empty string).
prevValue
of type DOMString
, readonlyprevValue
indicates the previous value of the Attr
node in DOMAttrModified
events, and of the CharacterData
node in DOMCharacterDataModified
events.
The un-initialized value of this attribute must be ""
(the empty string).
relatedNode
of type Node
, readonlyrelatedNode
must 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
will be the changed parent. If an event is instead dispatched to a subtree indicating a node was changed
within it, the relatedNode
must be the changed node. In the case of the DOMAttrModified
event it indicates the Attr
node which was modified, added, or removed.
The un-initialized value of this attribute must be null
.
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
.
The mutation event types are listed below.
DOMAttrModified
Type | DOMAttrModified |
---|---|
Interface | MutationEvent |
Sync / Async | Sync |
Bubbles | Yes |
Target | Element |
Cancelable | No |
Default action | none |
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 event target of this event must 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
Type | DOMCharacterDataModified |
---|---|
Interface | MutationEvent |
Sync / Async | Sync |
Bubbles | Yes |
Target | Text , Comment , CDATASection , ProcessingInstruction |
Cancelable | No |
Default action | none |
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 event target of this event must
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
Type | DOMNodeInserted |
---|---|
Interface | MutationEvent |
Sync / Async | Sync |
Bubbles | Yes |
Target | Element , Attr , Text , Comment , CDATASection , DocumentType , EntityReference ,
ProcessingInstruction |
Cancelable | No |
Default action | none |
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
event target of this event must be the node being inserted.
Note: for detecting attribute insertion, use the DOMAttrModified
event type 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
Type | DOMNodeInsertedIntoDocument |
---|---|
Interface | MutationEvent |
Sync / Async | Sync |
Bubbles | No |
Target | Element , Attr , Text , Comment , CDATASection , DocumentType , EntityReference ,
ProcessingInstruction |
Cancelable | No |
Default action | none |
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 treat an Attr
node as part of an Element
's subtree. This event must be dispatched after the insertion has taken place. The
event target of this event must 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
Type | DOMNodeRemoved |
---|---|
Interface | MutationEvent |
Sync / Async | Sync |
Bubbles | Yes |
Target | Element , Attr , Text , Comment , CDATASection , DocumentType , EntityReference ,
ProcessingInstruction |
Cancelable | No |
Default action | none |
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
event target of this event must be the node being removed.
Note: for reliably detecting attribute removal, use the DOMAttrModified
event type 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
Type | DOMNodeRemovedFromDocument |
---|---|
Interface | MutationEvent |
Sync / Async | Sync |
Bubbles | No |
Target | Element , Attr , Text , Comment , CDATASection , DocumentType , EntityReference ,
ProcessingInstruction |
Cancelable | No |
Default action | none |
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 treat an Attr
node as part of an Element
's subtree. This event must be dispatched before the removal takes place. The event
target of this event type must 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, use the DOMAttrModified
event type 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
Type | DOMSubtreeModified |
---|---|
Interface | MutationEvent |
Sync / Async | Sync |
Bubbles | Yes |
Target | defaultView , Document , DocumentFragment , Element , Attr
|
Cancelable | No |
Default action | none |
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 must 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.
This section contains necessary information regarding keyboard events:
Note: This section uses Serbian and Kanji characters which could be misrepresented or unavailable in the PDF version or printed version of this specification.
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.
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
). 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
'Shift'
and 'F'
keys.'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: the key legends for function keys do not normally produce any characters, although the symbol might have a Unicode equivalent; for example, the 'Shift'
key might bear the symbol ⇧
, which has the Unicode code point
'\u21E7'
, but pressing the 'Shift'
key will not produce this character value, and there is no
Unicode code point for 'Shift'
.
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'
('\u0071'
, Latin Small Letter Q). If
the keyboard layout mapping is switched to a French mapping, pressing the same key will produce the character 'a'
('\u0041'
,
Latin Capital Letter A). If the keyboard layout mapping is switched to a Serbian (Cyrillic) mapping, pressing the same key will produce the character
'љ'
('\u0459'
, 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
might 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: Don't confuse key values with scan codes, which are the low-level hexadecimal signals produced for each key
by the keyboard driver software. Scan codes are mapped at the operating system to a VK (virtual key
), which
in turn might be mapped to the user-defined key configuration. Key values are a high-level abstraction of that final mapping.
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 are expected to create content in an internationalized and localizable manner.
Figure 3: A graphical depiction of an ISO standard defining layouts of computer keyboards, ISO 9995, parts 2 and 3
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 are expected to create content in an internationalized and localizable manner.
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
Many keyboards contain special keys to control media functions. Increasingly, many media devices, especially televisions, are Web-enabled. Hybrid keyboard/remote-control devices are becoming more common. To meet the needs of these hybrid Web/media devices, this specification defines keys that are common as remote control buttons, in addition to traditional keyboard keys.
Because of the smaller form factor, keys (or buttons) on a remote control will often be modal, with one key performing different functions based on the context of the on-screen content. Additionally, many keys serve as toggles, to change back and forth between two or more states (see toggling keys).
Figure 5: A graphical depiction of a media remote control, with buttons mapped to specific keys values
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.
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.
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.
Note: While implementations will use the most relevant value for a key independently of the platform or keyboard layout mappings,
content authors can not make assumptions on the ability of keyboard devices to generate them. When using keyboard events and key values for shortcut-key combinations,
content authors can 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.
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 can map their keyboard to an arbitrary custom configuration, the content
author is encouraged not to 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 is encouraged instead to 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 might 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 the empty string.
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 '\u00D7'
) or the Latin small letter 'x'
(due to the lack of a multiplication key on many keyboards
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.
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.
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].
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 '\u0051'
) on a PC/AT US keyboard using a US mapping:
Example:
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:
Example:
The following example describes a possible sequence of keys that does not generate a Unicode character (using the same configuration):
Example:
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 will match the most appropriate function of the key in its current modified
state.
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:
keydown
: '\u0302'
(Combining Circumflex Accent key)compositionstart
: ''
compositionupdate
: '\u0302'
(Combining Circumflex Accent key)keyup
: '\u0302'
(Combining Circumflex Accent key)keydown
: 'ê'
('\u00EA'
, LATIN SMALL LETTER
E WITH CIRCUMFLEX)compositionend
: 'ê'
keyup
: 'e'
('\u0065'
, Latin Small Letter E key)Note: In step 5 above, 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.
This process might 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:
keydown
: '\u0302'
(Combining Circumflex Accent key)compositionstart
: ''
compositionupdate
: '\u0302'
(Combining Circumflex Accent key)keyup
: '\u0302'
(Combining Circumflex Accent key)keydown
: 'q'
('\u0071'
, The Latin Small Letter
Q key)compositionend
: ''
keyup
: 'q'
('\u0071'
, The Latin Small Letter
Q key)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 can 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.
Note: In some implementations or system configurations, some key events, or their values, might be suppressed by the IME in use.
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 can be respectively
'\u0020'
(Space key) and 'Enter'
.
Note: '詩'
(poem
) and '市'
(city
) are homophones, both
pronounced shi
, so the user would use the 'Convert'
key to select the proper option.
Example:
keydown
: 's'
('\u0073'
, Latin Small Letter
S key)compositionstart
: ''
keyup
: 's'
('\u0073'
, Latin Small Letter
S key)keydown
: 'i'
('\u0069'
, Latin Small Letter
I key)keyup
: 'i'
('\u0069'
, Latin Small Letter
I key)keydown
: 'Convert'
compositionupdate
: '詩'
keyup
: 'Convert'
keydown
: 'Convert'
compositionupdate
: '市'
keyup
: 'Convert'
keydown
: 'Accept'
compositionend
: '市'
keyup
: 'Accept'
IME composition can also be canceled as in the following example, with conditions identical to the previous example. The key
'Cancel'
might 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:
keydown
: 's'
('\u0073'
, Latin Small Letter
S key)compositionstart
: ''
keyup
: 's'
('\u0073'
, Latin Small Letter
S key)keydown
: 'i'
('\u0069'
, Latin Small Letter
I key)keyup
: 'i'
('\u0069'
, Latin Small Letter
I key)keydown
: 'Convert'
compositionupdate
: '詩'
keyup
: 'Convert'
keydown
: 'Convert'
compositionupdate
: '市'
keyup
: 'Convert'
keydown
: 'Cancel'
compositionupdate
: ''
compositionend
: ''
keyup
: 'Cancel'
Note: Some input method editors (such as on the MacOS operating system) might set an empty string to the composition data attribute before canceling a composition.
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 can 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 is expected to 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 might change to
the indicated mode, or a different IME might be launched, or the might 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: keys with input method editor functions are not restricted to that purpose, and can have other device- or implementation-specific purposes, as well.
Canceling the default action of a keydown
event
must not affect its respective keyup
event, but it must prevent the respective keypress
event (if supported) 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:
keydown
: 'Shift'
,
shiftKey
keydown
: 'Q'
('\u0051'
, Latin Capital
Letter Q key), shiftKey
keydown
event is
prevented, e.g., by invoking Event.preventDefault()
during the dispatch of the keydown
event objectkeypress
event is generatedkeyup
: 'Q'
('\u0051'
, Latin Capital Letter
Q key), shiftKey
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:
keydown
: 'Shift'
,
shiftKey
keydown
event is
prevented, e.g., by invoking Event.preventDefault()
during the dispatch of the keydown
event objectkeydown
: 'Q'
('\u0051'
, Latin Capital
Letter Q key), shiftKey
keypress
: 'Q'
keyup
: 'Q'
('\u0051'
, Latin Capital Letter
Q key), shiftKey
keyup
: 'Shift'
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 must 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 keypress
events (if supported). The following example uses the keystrokes '\u0302'
(Combining Circumflex Accent key) and the key marked
'e'
('\u0065'
, Latin Small Letter E key) (on a PC/AT french keyboard using a french mapping and without any modifier activated):
Example:
keydown
: '\u0302'
(Combining Circumflex Accent key)keydown
event is
prevented, e.g., by invoking Event.preventDefault()
during the dispatch of the keydown
event objectkeyup
: '\u0302'
(Combining Circumflex Accent key)keydown
: 'é'
('\u00E9'
, LATIN SMALL LETTER
E WITH ACUTE)keypress
: 'é'
keyup
: 'é'
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:
KeyboardEvent.key
attribute must be a string consisting of the key value of that character; andKeyboardEvent.char
attribute must be a string consisting of the char value of that character.KeyboardEvent.key
attribute must be a string consisting of the char value of that character; andKeyboardEvent.char
attribute must be a string consisting of the char value of that character.KeyboardEvent.key
attribute must be a string consisting of the key value of that character; andKeyboardEvent.char
attribute must be the empty string.'\u0030'
..'\u0039'
),
('\u0041'
..'\u005A'
), or
('\u0061'
..'\u007A'
), and must begin with a character in the range
('\u0041'
..'\u005A'
).
Examples:
'Q'
maps to the key values '5'
(unmodified) and '%'
(shifted). The primary function of this key
is to generate the character '5'
('\u0035'
). 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'
.'^'
key is as a
dead key for the circumflex diacritical mark. This corresponds to the combining Unicode character '\u0302'
. Since this character
is in general category
Mn, the key value will be '\u0302'
.'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 will be the key value.
'Calendar'
.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.
Implementations that are unable to identify a key must use the key value 'Unidentified'
.
Warning! Conforming implementations must only use this key value when there is no way for the implementation to detect the key value; exposing only this value must not indicate a conforming implementation.
The key values defined in this specification are based in part 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 key values for media controllers (e.g. remote controls for television, audio systems, and set-top boxes) are derived in part from the consumer electronics technical
specifications DTV Application Software Environment [DASE], Open Cable Application Platform 1.1.3 [OCAP],
and ANSI/CEA-2014-B, Web-based Protocol and Framework for Remote User Interface on UPnPTM Networks and the Internet [WEB4CE].
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 could 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 ("𣧂"
). Characters escaped in this manner:
The following list contains the normative list of case-sensitive key values, their character values (where applicable), an informative description of typical usage,
and an informative categorization. A conforming implementation of the KeyboardEvent interface must support at least this set
of values for use in the KeyboardEvent.char
and KeyboardEvent.key
attributes, though not all values may be available on all platforms or devices.
Key | Char | Typical Usage (Informative) | Category (Informative) |
---|---|---|---|
'Attn' |
The Attention (Attn) key. | General | |
'Apps' |
Toggle display of available (interactive) application list. | General | |
'Crsel' |
The Cursor Select (Crsel) key. | General | |
'ExSel' |
The Extend Selection (ExSel) key. | General | |
'F1' |
The F1 key, a general purpose function key, as index 1. | General | |
'F2' |
The F2 key, a general purpose function key, as index 2. | General | |
'F3' |
The F3 key, a general purpose function key, as index 3. | General | |
'F4' |
The F4 key, a general purpose function key, as index 4. | General | |
'F5' |
The F5 key, a general purpose function key, as index 5. | General | |
'F6' |
The F6 key, a general purpose function key, as index 6. | General | |
'F7' |
The F7 key, a general purpose function key, as index 7. | General | |
'F8' |
The F8 key, a general purpose function key, as index 8. | General | |
'F9' |
The F9 key, a general purpose function key, as index 9. | General | |
'F10' |
The F10 key, a general purpose function key, as index 10. | General | |
'F11' |
The F11 key, a general purpose function key, as index 11. | General | |
'F12' |
The F12 key, a general purpose function key, as index 12. | General | |
'F13' |
The F13 key, a general purpose function key, as index 13. | General | |
'F14' |
The F14 key, a general purpose function key, as index 14. | General | |
'F15' |
The F15 key, a general purpose function key, as index 15. | General | |
'F16' |
The F16 key, a general purpose function key, as index 16. | General | |
'F17' |
The F17 key, a general purpose function key, as index 17. | General | |
'F18' |
The F18 key, a general purpose function key, as index 18. | General | |
'F19' |
The F19 key, a general purpose function key, as index 19. | General | |
'F20' |
The F20 key, a general purpose function key, as index 20. | General | |
'F21' |
The F21 key, a general purpose function key, as index 21. | General | |
'F22' |
The F22 key, a general purpose function key, as index 22. | General | |
'F23' |
The F23 key, a general purpose function key, as index 23. | General | |
'F24' |
The F24 key, a general purpose function key, as index 24. | General | |
'LaunchApplication1' |
The Start Application One key. | General | |
'LaunchApplication2' |
The Start Application Two key. | General | |
'LaunchMail' |
The Start Mail key. | General | |
'List' |
Toggle display listing of currently available content or programs. | General | |
'Props' |
The properties (props) key. | General | |
'Soft1' |
General purpose virtual function key, as index 1. | General | |
'Soft2' |
General purpose virtual function key, as index 2. | General | |
'Soft3' |
General purpose virtual function key, as index 3. | General | |
'Soft4' |
General purpose virtual function key, as index 4. | General | |
'Accept' |
The Accept (Commit, OK) key. Accept current option or input method sequence conversion. | UI | |
'Again' |
The Again key, to redo or repeat an action. | UI | |
'Enter' |
The Enter key, to activate current selection or accept current input.
Note: This key value is also used for the |
UI | |
'Find' |
The Find key. | UI | |
'Help' |
Toggle display of help information. | UI | |
'Info' |
Toggle display of information about currently selected context or media. | UI | |
'Menu' |
Toggle display of content or system menu, if available. | UI | |
'ScrollLock' |
The Scroll Lock key, to toggle between scrolling and cursor movement modes. | UI | |
'Execute' |
The Execute key. | UI | |
'Cancel' |
'\u0018' |
The Cancel key. | UI |
'Esc' |
'\u001B' |
The Escape (Esc) key, to initiate an escape sequence. | UI |
'Exit' |
Exit current state or current application (as appropriate). | UI | |
'Zoom' |
Toggle between full-screen and scaled content, or alter magnification level. | UI | |
'Separator' |
The Separator key, for context-sensitive text separators. | Character | |
'Spacebar' |
'\u0020' |
The Space (Spacebar) key (' ' ). |
Character |
'Add' |
'\u002B' |
The Add key, or plus sign ('+' ).
Note: the Add key is usually found on the numeric keypad (e.g., the 10-key) on typical 101-key keyboards and usually requires the 'NumLock' state to be enabled. |
Character / Math |
'Subtract' |
'\u2212' |
The Subtract key, or minus sign ('−' ).
Note: the Subtract key is usually found on the numeric keypad (e.g., the 10-key) on typical 101-key keyboards and usually requires the 'NumLock' state to be enabled. |
Character / Math |
'Multiply' |
'\u002A' |
The Multiply key, or multiplication sign ('*' ).
Note: the Multiply key is usually found on the numeric keypad (e.g., the 10-key) on typical 101-key keyboards and usually requires the 'NumLock' state to be enabled. Note: This key value can be represented by different characters depending on context, including |
Character / Math |
'Divide' |
'\u00F7' |
The Divide key, or division sign ('÷' ).
Note: the Divide key is usually found on the numeric keypad (e.g., the 10-key) on typical 101-key keyboards and usually requires the 'NumLock' state to be enabled. |
Character / Math |
'Equals' |
'\u003D' |
The Equals key, or equals sign ('=' ).
Note: the Equals key is usually found on the numeric keypad (e.g., the 10-key) on typical 101-key keyboards and usually requires the 'NumLock' state to be enabled. |
Character / Math |
'Decimal' |
'\u2396' |
The Decimal key, or decimal separator key symbol ('.' ).
Note: the Decimal key is usually found on the numeric keypad (e.g., the 10-key) on typical 101-key keyboards and usually requires the 'NumLock' state to be enabled. Note: This key value can be represented by different characters due to localization, such as |
Character / Math |
'BrightnessDown' |
The Brightness Down key. Typically controls the display brightness. | Device | |
'BrightnessUp' |
The Brightness Up key. Typically controls the display brightness. | Device | |
'Camera' |
The Camera key. | Device | |
'Eject' |
Toggle removable media to eject (open) and insert (close) state. | Device | |
'Power' |
Toggle power state.
Note: Some devices might not expose this key to the operating environment. |
Device | |
'PrintScreen' |
The Print Screen (PrintScrn, SnapShot) key, to initiate print-screen function. | Device | |
'BrowserFavorites' |
The Browser Favorites key. | Browser | |
'BrowserHome' |
The Browser Home key, used with keyboard entry, to go to the home page. | Browser | |
'BrowserRefresh' |
The Browser Refresh key. | Browser | |
'BrowserSearch' |
The Browser Search key. | Browser | |
'BrowserStop' |
The Browser Stop key. | Browser | |
'HistoryBack' |
Navigate to previous content or page in current history. | Browser | |
'HistoryForward' |
Navigate to next content or page in current history. | Browser | |
'Left' |
The left arrow key, to navigate or traverse leftward. | Navigation | |
'PageDown' |
The Page Down key, to scroll down or display next page of content. | Navigation | |
'PageUp' |
The Page Up key, to scroll up or display previous page of content. | Navigation | |
'Right' |
The right arrow key, to navigate or traverse rightward. | Navigation | |
'Up' |
The up arrow key, to navigate or traverse upward. | Navigation | |
'UpLeft' |
The diagonal up-left arrow key, to navigate or traverse diagonally up and to the left. | Navigation | |
'UpRight' |
The diagonal up-right arrow key, to navigate or traverse diagonally up and to the right. | Navigation | |
'Down' |
The down arrow key, to navigate or traverse downward. | Navigation | |
'DownLeft' |
The diagonal down-left arrow key, to navigate or traverse diagonally down and to the left. | Navigation | |
'DownRight' |
The diagonal down-right arrow key, to navigate or traverse diagonally down and to the right. | Navigation | |
'Home' |
The Home key, used with keyboard entry, to go to start of content. | Edit / Navigation | |
'End' |
The End key, used with keyboard entry to go to the end of content. | Edit / Navigation | |
'Select' |
The Select key. | Edit / Navigation | |
'Tab' |
'\u0009' |
The Horizontal Tabulation (Tab) key. | Edit / Navigation |
'Backspace' |
'\u0008' |
The Backspace key. | Edit |
'Clear' |
The Clear key, for removing current selected input. | Edit | |
'Copy' |
The Copy key. | Edit | |
'Cut' |
The Cut key. | Edit | |
'Del' |
'\u007F' |
The Delete (Del) Key.
Note: This key value is also used for the key labeled |
Edit |
'EraseEof' |
The Erase to End of Field key. This key deletes all characters from the current cursor position to the end of the current field. | Edit | |
'Insert' |
The Insert (Ins) key, to toggle between text modes for insertion or overtyping. | Edit | |
'Paste' |
The Paste key. | Edit | |
'Undo' |
The Undo key. | Edit | |
'DeadGrave' |
'\u0300' |
The Combining Grave Accent (Greek Varia, Dead Grave) key. | Composition |
'DeadEacute' |
'\u0301' |
The Combining Acute Accent (Stress Mark, Greek Oxia, Tonos, Dead Eacute) key. | Composition |
'DeadCircumflex' |
'\u0302' |
The Combining Circumflex Accent (Hat, Dead Circumflex) key. | Composition |
'DeadTilde' |
'\u0303' |
The Combining Tilde (Dead Tilde) key. | Composition |
'DeadMacron' |
'\u0304' |
The Combining Macron (Long, Dead Macron) key. | Composition |
'DeadBreve' |
'\u0306' |
The Combining Breve (Short, Dead Breve) key. | Composition |
'DeadAboveDot' |
'\u0307' |
The Combining Dot Above (Derivative, Dead Above Dot) key. | Composition |
'DeadUmlaut' |
'\u0308' |
The Combining Diaeresis (Double Dot Abode, Umlaut, Greek Dialytika, Double Derivative, Dead Diaeresis) key. | Composition |
'DeadAboveRing' |
'\u030A' |
The Combining Ring Above (Dead Above Ring) key. | Composition |
'DeadDoubleacute' |
'\u030B' |
The Combining Double Acute Accent (Dead Doubleacute) key. | Composition |
'DeadCaron' |
'\u030C' |
The Combining Caron (Hacek, V Above, Dead Caron) key. | Composition |
'DeadCedilla' |
'\u0327' |
The Combining Cedilla (Dead Cedilla) key. | Composition |
'DeadOgonek' |
'\u0328' |
The Combining Ogonek (Nasal Hook, Dead Ogonek) key. | Composition |
'DeadIota' |
'\u0345' |
The Combining Greek Ypogegrammeni (Greek Non-Spacing Iota Below, Iota Subscript, Dead Iota) key. | Composition |
'DeadVoicedSound' |
'\u3099' |
The Combining Katakana-Hiragana Voiced Sound Mark (Dead Voiced Sound) key. | Composition |
'DeadSemivoicedSound' |
'\u309A' |
The Combining Katakana-Hiragana Semi-Voiced Sound Mark (Dead Semivoiced Sound) key. | Composition |
'Alphanumeric' |
The Alphanumeric key. | Modifier | |
'Alt' |
The Alternative (Alt, Option, Menu) key. Enable alternate modifier function for interpreting concurrent or subsequent keyboard input.
Note: This key value is also used for the Apple |
Modifier | |
'AltGraph' |
The Alt-Graph key. | Modifier | |
'CapsLock' |
The Caps Lock (Capital) key. Toggle capital character lock function for interpreting subsequent keyboard input event. | Modifier | |
'Control' |
The Control (Ctrl) key, to enable control modifier function for interpreting concurrent or subsequent keyboard input. | Modifier | |
'Fn' |
The Function switch (Fn) key. Activating this key simultaneously with another key changes that key's value to an alternate character or function. | Modifier | |
'FnLock' |
The Function-Lock (FnLock, F-Lock) key. Activating this key switches the mode of the keyboard to changes some keys' values to an alternate character or function. | Modifier | |
'Meta' |
The Meta key, to enable meta modifier function for interpreting concurrent or subsequent keyboard input.
Note: This key value is also used for the Apple |
Modifier | |
'Process' |
The Process key. | Modifier | |
'NumLock' |
The Number Lock key, to toggle numer-pad mode function for interpreting subsequent keyboard input. | Modifier | |
'Shift' |
The Shift key, to enable shift modifier function for interpreting concurrent or subsequent keyboard input. | Modifier | |
'SymbolLock' |
The Symbol Lock key. | Modifier | |
'OS' |
The operating system key (e.g. the Windows Logokey). |
Modifier | |
'Compose' |
The Compose key, also known as Multi_key on the X Window System. This key acts in a manner similar to a dead key, triggering a mode where subsequent key presses are combined to produce a different character. | Modifier | |
'AllCandidates' |
The All Candidates key, to initate the multi-candidate mode. | IME | |
'NextCandidate' |
The Next Candidate function key. | IME | |
'PreviousCandidate' |
The Previous Candidate function key. | IME | |
'CodeInput' |
The Code Input key, to initiate the Code Input mode to allow characters to be entered by their code points. | IME | |
'Convert' |
The Convert key, to convert the current input method sequence. | IME | |
'Nonconvert' |
The Nonconvert (Don't Convert) key, to accept current input method sequence without conversion in IMEs. | IME | |
'FinalMode' |
The Final Mode (Final) key used on some Asian keyboards, to enable the final mode for IMEs. | IME | |
'FullWidth' |
The Full-Width Characters key. | IME | |
'HalfWidth' |
The Half-Width Characters key. | IME | |
'ModeChange' |
The Mode Change key, to toggle between or cycle through input modes of IMEs. | IME | |
'RomanCharacters' |
The Roman Characters function key, also known as the 'Youngja' or 'Young' key. |
IME | |
'HangulMode' |
The Hangul (Korean characters) Mode key, to toggle between Hangul and English modes. | IME | |
'HanjaMode' |
The Hanja (Korean characters) Mode key. | IME | |
'JunjaMode' |
The Junja (Korean characters) Mode key. | IME | |
'Hiragana' |
The Hiragana (Japanese Kana characters) key. | IME | |
'JapaneseHiragana' |
The Japanese-Hiragana key. | IME | |
'JapaneseKatakana' |
The Japanese-Katakana key. | IME | |
'JapaneseRomaji' |
The Japanese-Romaji key. | IME | |
'KanaMode' |
The Kana Mode (Kana Lock) key. | IME | |
'KanjiMode' |
The Kanji (Japanese name for ideographic characters of Chinese origin) Mode key. | IME | |
'Katakana' |
The Katakana (Japanese Kana characters) key. | IME | |
'AudioFaderFront' |
Adjust audio fader towards front. | Media | |
'AudioFaderRear' |
Adjust audio fader towards rear. | Media | |
'AudioBalanceLeft' |
Adjust audio balance leftward. | Media | |
'AudioBalanceRight' |
Adjust audio balance rightward. | Media | |
'AudioBassBoostDown' |
Decrease audio bass boost or cycle down through bass boost states. | Media | |
'AudioBassBoostUp' |
Increase audio bass boost or cycle up through bass boost states. | Media | |
'AudioMute' |
Toggle between muted state and prior volume level. | Media | |
'AudioVolumeDown' |
Decrease audio volume. | Media | |
'AudioVolumeUp' |
Increase audio volume. | Media | |
'MediaPause' |
Pause playback, if not paused or stopped; also used with keyboard entry to pause scrolling output. | Media | |
'MediaPlay' |
Initiate or continue media playback at normal speed, if not currently playing at normal speed. | Media | |
'MediaTrackEnd' |
Seek to end of media or program. | Media | |
'MediaTrackNext' |
Seek to next media or program track. | Media | |
'MediaPlayPause' |
Toggle media between play and pause states. | Media | |
'MediaTrackPrevious' |
Seek to previous media or program track. | Media | |
'MediaTrackSkip' |
Skip current content or program. | Media | |
'MediaTrackStart' |
Seek to start of media or program. | Media | |
'MediaStop' |
Stop media playing, pausing, forwarding, rewinding, or recording, if not already stopped. | Media | |
'SelectMedia' |
The Select Media key. | Media | |
'Blue' |
General purpose color-coded media function key, as index 3. | Media | |
'Brown' |
General purpose color-coded media function key, as index 5. | Media | |
'ChannelDown' |
Select next (numerically or logically) lower channel.. | Media | |
'ChannelUp' |
Select next (numerically or logically) higher channel. | Media | |
'ClearFavorite0' |
Clear program or content stored as favorite 0. | Media | |
'ClearFavorite1' |
Clear program or content stored as favorite 1. | Media | |
'ClearFavorite2' |
Clear program or content stored as favorite 2. | Media | |
'ClearFavorite3' |
Clear program or content stored as favorite 3. | Media | |
'Dimmer' |
Adjust brightness of device, or toggle between or cycle through states. | Media | |
'DisplaySwap' |
Swap video sources. | Media | |
'FastFwd' |
Initiate or continue forward playback at faster than normal speed, or increase speed if already fast forwarding. | Media | |
'Green' |
General purpose color-coded media function key, as index 1. | Media | |
'Grey' |
General purpose color-coded media function key, as index 4. | Media | |
'Guide' |
Toggle display of program or content guide. | Media | |
'InstantReplay' |
Toggle instant replay. | Media | |
'MediaLast' |
Select previously selected channel or media. | Media | |
'Link' |
Launch linked content, if available and appropriate. | Media | |
'Live' |
Toggle display listing of currently available live content or programs. | Media | |
'Lock' |
Lock or unlock current content or program. | Media | |
'NextDay' |
If guide is active and displayed, then display next day's content. | Media | |
'NextFavoriteChannel' |
Select next favorite channel (in favorites list). | Media | |
'OnDemand' |
Access on-demand content or programs. | Media | |
'PinPDown' |
Move picture-in-picture window downward. | Media | |
'PinPMove' |
Move picture-in-picture window. | Media | |
'PinPToggle' |
Toggle display of picture-in-picture window. | Media | |
'PinPUp' |
Move picture-in-picture window upward. | Media | |
'PlaySpeedDown' |
Decrease media playback speed. | Media | |
'PlaySpeedReset' |
Reset playback speed to normal speed (according to current media function). | Media | |
'PlaySpeedUp' |
Increase media playback speed. | Media | |
'PrevDay' |
If guide is active and displayed, then display previous day's content. | Media | |
'RandomToggle' |
Toggle random media or content shuffle mode. | Media | |
'RecallFavorite0' |
Select (recall) program or content stored as favorite 0. | Media | |
'RecallFavorite1' |
Select (recall) program or content stored as favorite 1. | Media | |
'RecallFavorite2' |
Select (recall) program or content stored as favorite 2. | Media | |
'RecallFavorite3' |
Select (recall) program or content stored as favorite 3. | Media | |
'MediaRecord' |
Initiate or resume recording of currently selected media. | Media | |
'RecordSpeedNext' |
Toggle or cycle between media recording speeds (if applicable). | Media | |
'Red' |
General purpose color-coded media function key, as index 0. | Media | |
'MediaRewind' |
Initiate or continue reverse playback at faster than normal speed, or increase speed if already rewinding. | Media | |
'RfBypass' |
Toggle RF (radio frequency) input bypass mode. | Media | |
'ScanChannelsToggle' |
Toggle scan channels mode. | Media | |
'ScreenModeNext' |
Advance display screen mode to next available mode. | Media | |
'Settings' |
Toggle display of device settings screen. | Media | |
'SplitScreenToggle' |
Toggle split screen mode. | Media | |
'StoreFavorite0' |
Store current program or content as favorite 0. | Media | |
'StoreFavorite1' |
Store current program or content as favorite 1. | Media | |
'StoreFavorite2' |
Store current program or content as favorite 2. | Media | |
'StoreFavorite3' |
Store current program or content as favorite 3. | Media | |
'Subtitle' |
Toggle display of subtitles, if available. | Media | |
'AudioSurroundModeNext' |
Advance surround audio mode to next available mode. | Media | |
'Teletext' |
Toggle display of teletext, if available. | Media | |
'VideoModeNext' |
Advance video mode to next available mode. | Media | |
'DisplayWide' |
Toggle device display mode between wide aspect and normal aspect mode. | Media | |
'Wink' |
Cause device to identify itself in some manner, e.g., audibly or visibly. | Media | |
'Yellow' |
General purpose color-coded media function key, as index 2. | Media | |
'Unidentified' |
This key value is used when an implementations is unable to identify another key value, due to either hardware, platform, or software constraints. | Special |
This section is informative
This specification defines several new event interfaces without a mechanism for content authors to initialize their respective events.
These new event interfaces are:
In DOM Level 2 Events, the initialization of these event interfaces was possible through an init method on the interface (for example initMouseEvent
).
These init methods needed a long list of parameters that, in most cases, did not fully initialize all attributes of the event object. In order to fully initialize
an event interface which was derived from the basic Event
interface, it was necessary to call the initializer of each of the derived interfaces explicitly.
Example: Initializing all the attributes of a MutationEvent requires calls to two initializer methods: initEvent
and
initMutationEvent
.
Due in part to the length of time in the development of this standard, some implementations may have taken a dependency on a set of initializer methods that were formerly defined in this specification. For completeness, these legacy event intializers are described in this Appendix.
The initialization of new derived event objects becomes easier in DOM4 [DOM4] with the introduction of event constructors. Event constructors are a new mechanism for initializing the event object's attributes that allows authors to pick-and-choose which of all the possible event attributes should be initialized to a value. For the omitted values, a suitable default is applied.
This specification does not require a conforming implementation to support event constructors. Likewise it does not require a conforming implementation to support the legacy event initializers. However, it would be prudent for a conforming implementation to support one or the other, so that authors have some mechanism to initilize the new event interfaces defined in this specification.
Note: Event constructors are a relatively new concept and are subject to change. For the latest syntax, please refer to the DOM4 specification [DOM4].
This section is informative
This section documents legacy initializer methods and suggested event constructors for the following event interfaces introduced in DOM Level 3 Events:
For completeness, this section also documents suggested event constructors for the following event interfaces which were introduced in DOM Level 2 Events [DOM2 Events] but not deprecated in this specification:
// Event Constructor Syntax:
[Constructor(DOMString typeArg, optional EventInit eventInitDict)]
partial interface Event
{
};
// Suggested initEvent initializer:
dictionary EventInit {
boolean bubbles = false;
boolean cancelable = false;
};
// Event Constructor Syntax:
[Constructor(DOMString typeArg, optional CustomEventInit customEventInitDict)]
partial interface CustomEvent
{
// Originally introduced (and deprecated) in DOM Level 3:
void initCustomEvent(DOMString typeArg,
boolean canBubbleArg,
boolean cancelableArg,
any detailArg);
};
// Suggested initCustomEvent replacement initializer:
dictionary CustomEventInit {
// Attributes from Event:
boolean bubbles = false;
boolean cancelable = false;
// Attributes for CustomEvent:
any detail = null;
};
// Event Constructor Syntax:
[Constructor(DOMString typeArg, optional UIEventInit dictUIEventInit)]
partial interface UIEvent
{
};
// Suggested initUIEvent replacement initializer:
dictionary UIEventInit {
// Attributes from Event:
boolean bubbles = false;
boolean cancelable = false;
// Attributes for UIEvent:
AbstractView? view = null;
long detail = 0;
};
// Event Constructor Syntax:
[Constructor(DOMString typeArg, optional FocusEventInit focusEventInitDict)]
partial interface FocusEvent
{
// Originally introduced (and deprecated) in DOM Level 3:
void initFocusEvent(DOMString typeArg,
boolean canBubbleArg,
boolean cancelableArg,
AbstractView? viewArg,
long detailArg,
EventTarget? relatedTargetArg);
};
// Suggested initFocusEvent replacement initializer:
dictionary FocusEventInit {
// Attributes from Event:
boolean bubbles = false;
boolean cancelable = false;
// Attributes from UIEvent:
AbstractView? view = null;
long detail = 0;
// Attributes for FocusEvent:
EventTarget? relatedTarget = null;
};
// Event Constructor Syntax:
[Constructor(DOMString typeArg, optional MouseEventInit mouseEventInitDict)]
partial interface MouseEvent
{
};
// Suggested initMouseEvent replacement initializer:
dictionary MouseEventInit {
// Attributes from Event:
boolean bubbles = false;
boolean cancelable = false;
// Attributes from UIEvent:
AbstractView? view = null;
long detail = 0;
// Attributes for MouseEvent:
long screenX = 0;
long screenY = 0;
long clientX = 0;
long clientY = 0;
boolean ctrlKey = false;
boolean shiftKey = false;
boolean altKey = false;
boolean metaKey = false;
unsigned short button = 0;
// Note: "buttons" was not previously initializable through initMouseEvent!
unsigned short buttons = 0;
EventTarget? relatedTarget = null;
};
// Event Constructor Syntax:
[Constructor(DOMString typeArg, optional WheelEventInit wheelEventInitDict)]
partial interface WheelEvent
{
// Originally introduced (and deprecated) in DOM Level 3:
void initWheelEvent(DOMString typeArg,
boolean canBubbleArg,
boolean cancelableArg,
AbstractView? viewArg,
long detailArg,
long screenXArg,
long screenYArg,
long clientXArg,
long clientYArg,
unsigned short buttonArg,
EventTarget? relatedTargetArg,
DOMString modifiersListArg,
float deltaXArg,
float deltaYArg,
float deltaZArg,
unsigned long deltaMode);
};
// Suggested initWheelEvent replacement initializer:
dictionary WheelEventInit {
// Attributes from Event:
boolean bubbles = false;
boolean cancelable = false;
// Attributes from UIEvent:
AbstractView? view = null;
long detail = 0;
// Attributes from MouseEvent:
long screenX = 0;
long screenY = 0;
long clientX = 0;
long clientY = 0;
boolean ctrlKey = false;
boolean shiftKey = false;
boolean altKey = false;
boolean metaKey = false;
unsigned short button = 0;
// Note: "buttons" was not previously initializable through initMouseEvent!
unsigned short buttons = 0;
EventTarget? relatedTarget = null;
// Attributes for WheelEvent:
float deltaX = 0.0;
float deltaY = 0.0;
float deltaZ = 0.0;
unsigned long deltaMode = 0;
};
// Event Constructor Syntax:
[Constructor(DOMString typeArg, optional KeyboardEventInit keyboardEventInitDict)]
partial interface KeyboardEvent
{
// Originally introduced (and deprecated) in DOM Level 3:
void initKeyboardEvent(DOMString typeArg,
boolean canBubbleArg,
boolean cancelableArg,
AbstractView? viewArg,
DOMString charArg,
DOMString keyArg,
unsigned long locationArg,
DOMString modifiersListArg,
boolean repeat,
DOMString localeArg);
};
// Suggested initKeyboardEvent replacement initializer:
dictionary KeyboardEventInit {
// Attributes from Event:
boolean bubbles = false;
boolean cancelable = false;
// Attributes from UIEvent:
AbstractView? view = null;
long detail = 0;
// Attributes for KeyboardEvent:
DOMString char = "";
DOMString key = "";
unsigned long location = 0;
boolean ctrlKey = false;
boolean shiftKey = false;
boolean altKey = false;
boolean metaKey = false;
boolean repeat = false;
DOMString locale = "";
// (Legacy) key attributes for KeyboardEvent:
unsigned long charCode = 0;
unsigned long keyCode = 0;
unsigned long which = 0;
};
// Event Constructor Syntax:
[Constructor(DOMString typeArg, optional CompositionEventInit compositionEventInitDict)]
partial interface CompositionEvent
{
// Originally introduced (and deprecated) in DOM Level 3:
void initCompositionEvent(DOMString typeArg,
boolean canBubbleArg,
boolean cancelableArg,
AbstractView? viewArg,
DOMString? dataArg,
DOMString localeArg);
};
// Suggested initCompositionEvent replacement initializer:
dictionary CompositionEventInit {
// Attributes from Event:
boolean bubbles = false;
boolean cancelable = false;
// Attributes from UIEvent:
AbstractView? view = null;
long detail = 0;
// Attributes for CompositionEvent:
DOMString? data = null;
DOMString locale = "";
};
initCustomEvent
Initializes attributes of a CustomEvent
object. This method has the same behavior as Event.initEvent()
.
Warning! The initCustomEvent
method is deprecated. Event constructor syntax, introduced in DOM4, is the expected future
syntax for initializing a CustomEvent
.
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 any
Specifies CustomEvent.detail
.
initFocusEvent
Initializes attributes of a FocusEvent
object. This method has the same behavior as UIEvent.initUIEvent()
.
Warning! The initFocusEvent
method is deprecated. Event constructor syntax, introduced in DOM4, is the expected future
syntax for initializing a FocusEvent
.
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 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
.
initWheelEvent
Initializes attributes of a WheelEvent
object. This method has the same behavior as MouseEvent.initMouseEvent()
.
Warning! The initWheelEvent
method is deprecated. Event constructor syntax, introduced in DOM4, is the expected future
syntax for initializing a WheelEvent
.
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 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
A white space separated list of modifier key values to be activated
on this object. As an example, "Control Shift"
marks the control and shift modifiers as activated (the
MouseEvent.ctrlKey
and MouseEvent.shiftKey
inherited attributes will be true
on the initialized WheelEvent
object).
deltaXArg
of type float
Specifies WheelEvent.deltaX
.
deltaYArg
of type float
Specifies WheelEvent.deltaY
.
deltaZArg
of type float
Specifies WheelEvent.deltaZ
.
deltaModeArg
of type unsigned long
Specifies WheelEvent.deltaMode
.
initKeyboardEvent
Initializes attributes of a KeyboardEvent
object. This method has the same behavior as UIEvent.initUIEvent()
.
The value of UIEvent.detail
remains undefined.
Warning! The initKeyboardEvent
method is deprecated. Event constructor syntax, introduced in DOM4, is the expected
future syntax for initializing a KeyboardEvent
.
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 AbstractView
Refer to the UIEvent.initUIEvent()
method for a description of this parameter.
charArg
of type DOMString
Specifies KeyboardEvent.char
.
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"
marks the control and alt modifiers as activated.
repeatArg
of type boolean
Specifies whether the key event is repeating; see KeyboardEvent.repeat
.
localeArg
of type DOMString
Specifies KeyboardEvent.locale
.
initCompositionEvent
Initializes attributes of a CompositionEvent
object. This method has the same behavior as UIEvent.initUIEvent()
.
The value of UIEvent.detail
remains undefined.
Warning! The initCompositionEvent
method is deprecated. Event constructor syntax, introduced in DOM4, is the expected
future syntax for initializing a CompositionEvent
.
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 AbstractView
Refer to the UIEvent.initUIEvent()
method for a description of this parameter.
dataArg
of type DOMString
Specifies CompositionEvent.data
.
localeArg
of type DOMString
Specifies CompositionEvent.locale
.
keyCode
, charCode
, and which
This section is informative
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 charCode
, keyCode
, or which
attributes on the KeyboardEvent interface, though they may be present in
user agents for compatibility with legacy content. Authors should use the KeyboardEvent.char
and
KeyboardEvent.key
attributes instead of the charCode
and keyCode
attributes, respectively.
However, for the purpose of documenting the current state of these attributes and their relation to equivalent key values, this section describes an informative Web IDL partial interface for KeyboardEvent containing these attributes, and informative definitions for determining their attribute values.
For implementations which do support these attributes, it is suggested to use this partial KeyboardEvent interface.
The partial KeyboardEvent
interface is an informative extension of the KeyboardEvent interface, which adds the
charCode, keyCode, and
which attributes.
The partial KeyboardEvent
interface can be obtained by using the DocumentEvent.createEvent("KeyboardEvent")
method call in implementations that support this extension.
// introduced in DOM Level 3:
partial interface KeyboardEvent
{
// The following support legacy user agents:
readonly attribute unsigned long charCode;
readonly attribute unsigned long keyCode;
readonly attribute unsigned long which;
};
charCode
of type
unsigned long
, readonlycharCode
holds a character value, for keypress
events which
generate character input. The value is the Unicode reference number (code point) of that character (e.g. event.charCode = event.char.charCodeAt(0)
).
For keydown
or keyup
events, the
value of charCode
is 0
.
keyCode
of type unsigned long
, readonlykeyCode
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 normatively 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 use the key value '0'
.
See Legacy key models for more details on how to determine the values for keyCode
.
which
of type unsigned
long
, readonlywhich
holds a system- and implementation-dependent numerical code signifying the unmodified identifier associated with the key pressed. In most cases,
the value is identical to keyCode
.
This section is informative
Implementations differ on which values are exposed on these attributes for different event types. An implementation may choose to expose both virtual key codes
and character codes in the keyCode
property (conflated model), or report separate keyCode
and charCode
properties (split model).
keyCode
for keydown
and keyup
eventsThe keyCode
for keydown
or
keyup
events is calculated as follows:
keydown
, return 229.keyCode
for keypress
eventsThis section is informative
The keyCode
for keypress
events is calculated as follows:
keyCode
to the Unicode code point of the character being entered.
keyCode
to 0.This section is informative
The virtual key codes for the following keys do not usually change with keyboard layouts on desktop systems:
Key | Virtual Key Code |
---|---|
'Backspace' |
8 |
'Tab' |
9 |
'Enter' |
13 |
'Shift' |
16 |
'Control' |
17 |
'Alt' |
18 |
'CapsLock' |
20 |
'Esc' (Escape) |
27 |
'Spacebar' (Space) |
32 |
'PageUp' |
33 |
'PageDown' |
34 |
'End' |
35 |
'Home' |
36 |
'Left' |
37 |
'Up' |
38 |
'Right' |
39 |
'Down' |
40 |
'Del' (Delete) |
46 |
This section is informative
The following punctuation characters may change virtual codes between keyboard layouts, but reporting these values will likely be more compatible with legacy content expecting US-English keyboard layout:
Key | Virtual Key Code |
---|---|
Semicolon (';' ) |
186 |
Colon (':' ) |
186 |
Plus ('+' ) |
187 |
Equals sign ('=' ) |
187 |
Comma (',' ) |
188 |
Less than sign ('<' ) |
188 |
Minus ('-' ) |
189 |
Underscore ('_' ) |
189 |
Period ('.' ) |
190 |
Greater than sign ('>' ) |
190 |
Question mark ('?' ) |
191 |
Forward slash ('/' ) |
191 |
Backtick ('`' ) |
192 |
Tilde ('~' ) |
192 |
Opening square bracket ('[' ) |
219 |
Opening curly bracket ('{' ) |
219 |
Backslash ('\' ) |
220 |
Pipe ('|' ) |
220 |
Closing square bracket (']' ) |
221 |
Closing curly bracket ('}' ) |
221 |
Single quote (''' ) |
222 |
Double quote ('"' ) |
222 |
This section is informative
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 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 might 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 has to 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);
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
, might 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 might 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)
.
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 , O |
Presto (Opera Software) |
webkit |
WebKit (Apple, Google, others) |
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 might choose to dispatch no load
events to nodes that attempt to embed resources on the local network.
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.
This new specification introduced the following new concepts in the event flow:
window
), to reflect existing implementations.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 used by the event types.
"MutationEvents"
have been deprecated. Support for namespaced events, present in early drafts of this specification, has also 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.
Event
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.Event.type
attribute to be case-sensitive, while DOM Level 2 Events considers
Event.type
to be case-insensitive.EventTarget
EventTarget.dispatchEvent()
was modified.MouseEvent
MouseEvent
interface has one new method MouseEvent.getModifierState()
.EventException
EventException
is removed in this specification. The prior DISPATCH_REQUEST_ERR
code is re-mapped to a DOMException
of type InvalidStateError
.The interfaces CustomEvent
, FocusEvent
,
KeyboardEvent
, CompositionEvent
, and WheelEvent
were added to the Events module.
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:
key identifierfeature has been renamed
key valueto disambiguate them from unique identifiers for keys.
change
, submit
, and reset
events were removed, since they were specific to HTML forms, and are specified in [HTML5].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), and T.V. Raman (Google).
Contributors: In the WebApps Working Group, the following people made substantial material contributions in the process of refining and revising this specification: Olli Pettay (Mozilla), Hallvord R. M. Steen (Opera), Travis Leithead (Microsoft), Hironori Bono (Google), Daniel Danilatos (Google), Glenn Adams (Samsung), Mark Vickers (Comcast), Bob Lund (Cable Laboratories) and Cameron McCormack (Invited Expert / Mozilla), .
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.
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, Oliver Hunt, Alexey Proskuryakov, Giuseppe Pascale, and Jan Goyvaerts (regular-expressions.info).
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.
For the latest version of any W3C specification please consult the list of W3C Technical Reports available at http://www.w3.org/TR/.