1. Introduction
1.1. Overview
UI 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 UI Events is to provide a common subset of the current event systems used in existing browsers. This is intended to foster interoperability of existing scripts and content. It is not expected that this goal will be met with full backwards compatibility. However, the specification attempts to achieve this when possible.
1.2. Conformance
This section is normative.
Within this specification, the key words MUST
, MUST NOT
, REQUIRED
, SHALL
, SHALL NOT
, SHOULD
, SHOULD NOT
, RECOMMENDED
, MAY
, and OPTIONAL
are to be interpreted as described in [RFC2119].
This specification is to be understood in the context of the DOM Level 3
Core specification [DOM-Level-3-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 [DOM-Level-3-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 UI Events user agent MUST
support the DOMString
data type as defined in [WebIDL], but
need not support every method or data type defined in [WebIDL] in order
to conform to UI Events).
This specification defines several classes of conformance for different user agents, specifications, and content authors:
1.2.1. Web browsers and other dynamic or interactive user agents
A dynamic or interactive user agent, referred to here as a browser
(be it a Web browser, AT (Accessibility Technology)
application, or other similar program), conforms to UI Events if it
supports:
-
the Core module defined in [DOM-Level-3-Core]
-
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)
-
the complete set of
key
andcode
values defined in [UIEvents-Key] and [UIEvents-Code] (subject to platform availability), and -
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 UI Events if it implements the interfaces and related event types specified in this document.
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 interfaces, events, or other features defined in this specification, 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 UI 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].
1.2.2. Authoring tools
A content authoring tool conforms to UI Events if it produces content which uses the event types, consistent in a manner as defined in this specification.
A content authoring tool MUST NOT claim conformance to UI 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.
1.2.3. Content authors and content
A content author creates conforming UI Events content if that content uses the event types 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.
Content authors are advised to follow best practices as described in accessibility and internationalization guideline specifications.
1.2.4. Specifications and host languages
A specification or host language conforms to UI Events if it references and uses the event flow mechanism, interfaces, events, or other features defined in [DOM], and does not extend these features in incompatible ways.
A specification or host language conforms specifically to UI Events if it references and uses the interfaces and related event types specified in this document. A conforming specification MAY define additional interfaces and event types appropriate to that specification, or MAY extend the UI 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 UI 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).
2. Stylistic Conventions
This specification follows the Proposed W3C Specification Conventions, with the following supplemental additions:
-
The key cap printed on a key is shown as
↓
,=
orQ
. This is used to refer to a key from the user’s perspective without regard for thekey
andcode
values in the generatedKeyboardEvent
. -
Glyphs representing character are shown as:
"𣧂"
. -
Unicode character encodings are shown as:
U+003d
. -
Names of key values generated by a key press (i.e., the value of
KeyboardEvent
.key
) are shown as:"ArrowDown"
,"="
,"q"
or"Q"
. -
Names of key codes associated with the physical keys (i.e., the value of
KeyboardEvent
.code
) are shown as:"ArrowDown"
,"Equal"
or"KeyQ"
.
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.
And finally:
This is a note.
This is an open issue.
This is a warning.
interface Example { // This is an IDL definition. };
3. Basic Event Interfaces
The basic event interfaces defined in [DOM] are fundamental to UI Events. These basic event interfaces MUST always be supported by the implementation:
-
The
Event
interface and its following constants, methods and attributes:-
NONE
constant -
CAPTURING_PHASE
constant -
AT_TARGET
constant -
BUBBLING_PHASE
constant -
type
attribute -
target
attribute -
currentTarget
attribute -
eventPhase
attribute -
bubbles
attribute -
cancelable
attribute -
composed
attribute -
timeStamp
attribute -
defaultPrevented
attribute -
isTrusted
attribute -
stopPropagation()
method -
stopImmediatePropagation()
method -
preventDefault()
method -
initEvent()
method
-
-
The
CustomEvent
interface and its following method and attribute:-
initCustomEvent()
method -
detail
attribute
-
-
The
EventTarget
interface and its following methods:-
addEventListener()
method -
removeEventListener()
method -
dispatchEvent()
method
-
-
The
EventListener
interface and itshandleEvent()
method -
The
Document
interface’screateEvent()
method
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.
The following chart describes the inheritance structure of the interfaces described in this specification.
3.1. List of Event Types
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] 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 described in this specification.
Event Type | Sync / Async | Bubbling Phase | Trusted event target types | DOM Interface | Cancelable | Default Action |
---|---|---|---|---|---|---|
abort
| Sync | No | Window, Element | Event
| No | None |
auxclick
| Sync | Yes | Element | PointerEvent
| Yes | Varies |
beforeinput
| Sync | Yes | Element | InputEvent
| Yes | Update the DOM element |
blur
| Sync | No | Window, Element | FocusEvent
| No | None |
click
| Sync | Yes | Element | PointerEvent
| Yes | Varies: for targets with an associated activation behavior, executes the activation behavior; for focusable targets, gives the element focus. |
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 |
contextmenu
| Sync | Yes | Element | PointerEvent
| Yes | Invoke a context menu if supported |
dblclick
| Sync | Yes | Element | MouseEvent
| No | Varies: for targets with an associated activation behavior, executes the activation behavior; for focusable targets, gives the element focus. |
error
| Async | No | Window, Element | Event
| No | None |
focus
| Sync | No | Window, Element | FocusEvent
| No | None |
focusin
| Sync | Yes | Window, Element | FocusEvent
| No | None |
focusout
| Sync | Yes | Window, Element | FocusEvent
| No | None |
input
| Sync | Yes | Element | InputEvent
| No | None |
keydown
| Sync | Yes | Element | KeyboardEvent
| Yes | Varies: trigger beforeinput and input events; launch text composition system; blur and focus events; keypress event (if supported); activation behavior; other events
|
keyup
| Sync | Yes | Element | KeyboardEvent
| Yes | None |
load
| Async | No | Window, 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 | None |
select
| Sync | Yes | Element | Event
| No | None |
unload
| Sync | No | Window, Document, Element | Event
| No | None |
wheel
| Async | Yes | Element | WheelEvent
| Yes | Scroll (or zoom) the document |
For a list of events which are deprecated in this specification, see the Legacy Event Types appendix at the end of this document.
The following is one way to interpret the above tables: 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 Window, Document
, or Element
nodes, or if it is attached to the bubbling phase
only, this event listener would not be triggered.
Don’t interpret the above tables 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
.
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.
3.2. User Interface Events
The User Interface event module contains basic event types associated with user interfaces and document manipulation.
3.2.1. Interface UIEvent
Introduced in DOM Level 2
The UIEvent
interface provides specific contextual information
associated with User Interface events.
To create an instance of the UIEvent
interface, use the UIEvent
constructor, passing an optional UIEventInit
dictionary.
For newly defined events, you don’t have to inherit UIEvent
interface just
because they are related to user interface. Inherit only when members of UIEventInit
make sense to those events.
3.2.1.1. UIEvent
[Exposed =Window ]interface :
UIEvent Event {(
constructor DOMString ,
type optional UIEventInit = {});
eventInitDict readonly attribute Window ?;
view readonly attribute long ; };
detail
UIEvent . view
-
The
view
attribute identifies theWindow
from which the event was generated.The un-initialized value of this attribute MUST be
null
. UIEvent . detail
-
Specifies some detail information about the
Event
, depending on the type of event.The un-initialized value of this attribute MUST be
0
.
3.2.1.2. UIEventInit
dictionary :
UIEventInit EventInit {Window ?=
view null ;long = 0; };
detail
UIEventInit . view
- Should be initialized to the Window object of the global
environment in which this event will be dispatched. If this
event will be dispatched to an element, the view property should
be set to the Window object containing the element’s
ownerDocument
. UIEventInit . detail
- This value is initialized to a number that is application-specific.
3.2.2. UIEvent Algorithms
3.2.2.1. initialize a UIEvent
- Input
-
event, the
UIEvent
to initializeeventType, a DOMString containing the event type
eventTarget, the
EventTarget
of the eventbubbles, true if this event bubbles
cancelable, true if this event is cancelable
- Output
-
None
-
Initialize the base
Event
attributes:-
Initialize an Event with event, eventType, bubbles and cancelable
-
Set event.
target
= eventTarget
-
-
Initialize the following public attributes:
-
Set event.
view
= the eventTarget’s node document’sWindow
object -
Set event.
detail
= 0
-
-
Initialize the following historical attributes:
-
Set event.
which
= 0 (used by bothMouseEvent
andKeyboardEvent
)
-
3.2.3. UIEvent Types
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.
3.2.3.1. load
Type | load
|
---|---|
Interface | UIEvent if generated from a user interface, Event otherwise.
|
Sync / Async | Async |
Bubbles | No |
Trusted Targets | Window , Document , Element
|
Cancelable | No |
Default action | None |
Context (trusted events) |
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.
For legacy reasons, load
events for resources inside the
document (e.g., images) do not include the Window in the
propagation path in HTML implementations. See [HTML5] for more
information.
3.2.3.2. unload
Type | unload
|
---|---|
Interface | UIEvent if generated from a user interface, Event otherwise.
|
Sync / Async | Sync |
Bubbles | No |
Trusted Targets | Window , Document , Element
|
Cancelable | No |
Default action | None |
Context (trusted events) |
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.
3.2.3.3. abort
Type | abort
|
---|---|
Interface | UIEvent if generated from a user interface, Event otherwise.
|
Sync / Async | Sync |
Bubbles | No |
Trusted Targets | Window , Element
|
Cancelable | No |
Default action | None |
Context (trusted events) |
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.
3.2.3.4. error
Type | error
|
---|---|
Interface | UIEvent if generated from a user interface, Event otherwise.
|
Sync / Async | Async |
Bubbles | No |
Trusted Targets | Window , Element
|
Cancelable | No |
Default action | None |
Context (trusted events) |
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.
3.2.3.5. select
Type | select
|
---|---|
Interface | UIEvent if generated from a user interface, Event otherwise.
|
Sync / Async | Sync |
Bubbles | Yes |
Trusted Targets | Element
|
Cancelable | No |
Default action | None |
Context (trusted events) |
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.
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 [Editing].
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.
3.3. Focus Events
This interface and its associated event types and § 3.3.2 Focus Event Order were designed in accordance to the concepts and guidelines defined in User Agent Accessibility Guidelines 2.0 [UAAG20], with particular attention on the focus mechanism and the terms defined in the glossary entry for focus.
3.3.1. Interface FocusEvent
Introduced in this specification
The FocusEvent
interface provides specific contextual information
associated with Focus events.
To create an instance of the FocusEvent
interface, use the
FocusEvent constructor, passing an optional FocusEventInit
dictionary.
3.3.1.1. FocusEvent
[Exposed =Window ]interface :
FocusEvent UIEvent {(
constructor DOMString ,
type optional FocusEventInit = {});
eventInitDict readonly attribute EventTarget ?; };
relatedTarget
FocusEvent . relatedTarget
-
Used to identify a secondary
EventTarget
related to a Focus event, depending on the type of event.For security reasons with nested browsing contexts, when tabbing into or out of a nested context, the relevant
EventTarget
SHOULD benull
.The un-initialized value of this attribute MUST be
null
.
3.3.1.2. FocusEventInit
dictionary :
FocusEventInit UIEventInit {EventTarget ?=
relatedTarget null ; };
FocusEventInit . relatedTarget
- The
relatedTarget
should be initialized to the element losing focus (in the case of afocus
orfocusin
event) or the element gaining focus (in the case of ablur
orfocusout
event).
3.3.2. Focus Event Order
The focus events defined in this specification occur in a set order relative to one another. The following is the typical sequence of events when a focus is shifted between elements (this order assumes that no element is initially focused):
Event Type | Notes | |
---|---|---|
User shifts focus | ||
1 | focus
| Sent after first target element receives focus |
2 | focusin
| Follows the focus event |
User shifts focus | ||
3 | blur
| Sent after first target element loses focus |
4 | focusout
| Follows the blur event |
5 | focus
| Sent after second target element receives focus |
6 | focusin
| Follows the focus event |
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.
3.3.3. Document Focus and Focus Context
This event module includes event types for notification of changes in document focus. There are three distinct focus contexts that are relevant to this discussion:
-
The operating system focus context which MAY be on one of many different applications currently running on the computer. One of these applications with focus can be a browser.
-
When the browser has focus, the user can switch (such as with the tab key) the application focus context among the different browser user interface fields (e.g., the Web site location bar, a search field, etc.). One of these user interface fields can be the document being shown in a tab.
-
When the document itself has focus, the document focus context can be set to any of 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.
3.3.4. Focus Event Types
The Focus event types are listed below.
3.3.4.1. blur
Type | blur
|
---|---|
Interface | FocusEvent
|
Sync / Async | Sync |
Bubbles | No |
Trusted Targets | Window , Element
|
Cancelable | No |
Composed | Yes |
Default action | None |
Context (trusted events) |
|
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 does not bubble.
3.3.4.2. focus
Type | focus
|
---|---|
Interface | FocusEvent
|
Sync / Async | Sync |
Bubbles | No |
Trusted Targets | Window , Element
|
Cancelable | No |
Composed | Yes |
Default action | None |
Context (trusted events) |
|
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 does not bubble.
3.3.4.3. focusin
Type | focusin
|
---|---|
Interface | FocusEvent
|
Sync / Async | Sync |
Bubbles | Yes |
Trusted Targets | Window , Element
|
Cancelable | No |
Composed | Yes |
Default action | None |
Context (trusted events) |
|
A user agent MUST dispatch this event when an event target receives focus. The event target MUST be the element which received focus. The focus event MUST fire before the dispatch of this event type. This event type is similar to focus, but does bubble.
3.3.4.4. focusout
Type | focusout
|
---|---|
Interface | FocusEvent
|
Sync / Async | Sync |
Bubbles | Yes |
Trusted Targets | Window , Element
|
Cancelable | No |
Composed | Yes |
Default action | None |
Context (trusted events) |
|
A user agent MUST dispatch this event when an event target loses focus. The event target MUST be the element which lost focus. The blur event MUST fire before the dispatch of this event type. This event type is similar to blur, but does bubble.
3.4. Mouse Events
The mouse event module originates from the [HTML401] 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.
3.4.1. Interface MouseEvent
Introduced in DOM Level 2, modified in this specification
The MouseEvent
interface provides specific contextual information
associated with Mouse events.
In the case of nested elements, mouse events are always targeted at the most deeply nested element.
Ancestors of the targeted element 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 MouseEvent
constructor, passing an optional MouseEventInit
dictionary.
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
).
3.4.1.1. MouseEvent
[Exposed =Window ]interface :
MouseEvent UIEvent {(
constructor DOMString ,
type optional MouseEventInit = {});
eventInitDict readonly attribute long screenX ;readonly attribute long screenY ;readonly attribute long clientX ;readonly attribute long clientY ;readonly attribute long layerX ;readonly attribute long layerY ;readonly attribute boolean ctrlKey ;readonly attribute boolean shiftKey ;readonly attribute boolean altKey ;readonly attribute boolean metaKey ;readonly attribute short button ;readonly attribute unsigned short buttons ;readonly attribute EventTarget ?relatedTarget ;boolean getModifierState (DOMString ); };
keyArg
screenX
, of type long, readonly-
The 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, readonly-
The 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
. clientX
, of type long, readonly-
The 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, readonly-
The 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
. layerX
, of type long, readonly-
The horizontal offset from the nearest ancestor element which
is a stacking context, is positioned, or paints in the
positioned phase when painting a stacking context.
The un-initialized value of this attribute MUST be
0
. layerY
, of type long, readonly-
The vertical offset from the nearest ancestor element which
is a stacking context, is positioned, or paints in the
positioned phase when painting a stacking context.
The un-initialized value of this attribute MUST be
0
. ctrlKey
, of type boolean, readonly-
Refer to the
KeyboardEvent
'sctrlKey
attribute.The un-initialized value of this attribute MUST be
false
. shiftKey
, of type boolean, readonly-
Refer to the
KeyboardEvent
'sshiftKey
attribute.The un-initialized value of this attribute MUST be
false
. altKey
, of type boolean, readonly-
Refer to the
KeyboardEvent
'saltKey
attribute.The un-initialized value of this attribute MUST be
false
. metaKey
, of type boolean, readonly-
Refer to the
KeyboardEvent
'smetaKey
attribute.The un-initialized value of this attribute MUST be
false
. button
, of type short, readonly-
During mouse events caused by the depression or release of a mouse button,
button
MUST be used to indicate which pointer device button changed state.The value of the
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). -
3
MUST indicate the X1 (back) button. -
4
MUST indicate the X2 (forward) button.
Some pointing devices provide or simulate more button states, and values higher than
2
or lower than0
MAY be used to represent such buttons.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 value0
as the left button, but rather as the un-initialized value.Some default actions related to events such as
mousedown
andmouseup
depend on the specific mouse button in use.The un-initialized value of this attribute MUST be
0
. -
buttons
, of type unsigned short, readonly-
During any mouse events,
buttons
MUST be used to indicate which combination of mouse buttons are currently being pressed, expressed as a bitmask.Though similarly named, the values for the
buttons
attribute and thebutton
attribute are very different. The value ofbutton
is assumed to be valid duringmousedown
/mouseup
event handlers, whereas thebuttons
attribute reflects the state of the mouse’s buttons for any trustedMouseEvent
object (while it is being dispatched), because it can represent the "no button currently active" state (0).The value of the
buttons
attribute MUST be as follows:-
0
MUST indicate 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
, ... ).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. For example, the value
3
indicates that the left and right button are currently both pressed, while the value5
indicates that the left and middle button are currently both pressed.Some default actions related to events such as
mousedown
andmouseup
depend on the specific mouse button in use.The un-initialized value of this attribute MUST be
0
. -
relatedTarget
, of type EventTarget, readonly, nullable-
Used 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
. getModifierState(keyArg)
-
Introduced in this specification
Queries the state of a modifier using a key value.
Returns
true
if it is a modifier key and the modifier is activated,false
otherwise.- DOMString keyArg
- Refer to the
KeyboardEvent
'sgetModifierState()
method for a description of this parameter.
3.4.1.2. MouseEventInit
dictionary :
MouseEventInit EventModifierInit {long screenX = 0;long screenY = 0;long clientX = 0;long clientY = 0;short button = 0;unsigned short buttons = 0;EventTarget ?relatedTarget =null ; };
screenX
, of type long, defaulting to0
-
Initializes the
screenX
attribute of theMouseEvent
object to the desired horizontal relative position of the mouse pointer on the user’s screen.Initializing the event object to the given mouse position must not move the user’s mouse pointer to the initialized position.
screenY
, of type long, defaulting to0
-
Initializes the
screenY
attribute of theMouseEvent
object to the desired vertical relative position of the mouse pointer on the user’s screen.Initializing the event object to the given mouse position must not move the user’s mouse pointer to the initialized position.
clientX
, of type long, defaulting to0
-
Initializes the
clientX
attribute of theMouseEvent
object to the desired horizontal position of the mouse pointer relative to the client window of the user’s browser.Initializing the event object to the given mouse position must not move the user’s mouse pointer to the initialized position.
clientY
, of type long, defaulting to0
-
Initializes the
clientY
attribute of theMouseEvent
object to the desired vertical position of the mouse pointer relative to the client window of the user’s browser.Initializing the event object to the given mouse position must not move the user’s mouse pointer to the initialized position.
button
, of type short, defaulting to0
-
Initializes the
button
attribute of theMouseEvent
object to a number representing the desired state of the button(s) of the mouse.The value 0 is used to represent the primary mouse button, 1 is used to represent the auxiliary/middle mouse button, and 2 to represent the right mouse button. Numbers greater than 2 are also possible, but are not specified in this document.
buttons
, of type unsigned short, defaulting to0
-
Initializes the
buttons
attribute of theMouseEvent
object to a number representing one or more of the button(s) of the mouse that are to be considered active.The
buttons
attribute is a bit-field. If a mask value of 1 is true when applied to the value of the bit field, then the primary mouse button is down. If a mask value of 2 is true when applied to the value of the bit field, then the right mouse button is down. If a mask value of 4 is true when applied to the value of the bit field, then the auxiliary/middle button is down.In JavaScript, to initialize the
buttons
attribute as if the right (2) and middle button (4) were being pressed simultaneously, the buttons value can be assigned as either:
{ buttons: 2 | 4 }
or:
{ buttons: 6 }
relatedTarget
, of type EventTarget, nullable, defaulting tonull
- The
relatedTarget
should be initialized to the element whose bounds the mouse pointer just left (in the case of a mouseover or mouseenter event) or the element whose bounds the mouse pointer is entering (in the case of a mouseout or mouseleave or focusout event). For other events, this value need not be assigned (and will default to 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.
3.4.2. Event Modifier Initializers
The MouseEvent
and KeyboardEvent
interfaces share a set of
keyboard modifier attributes and support a mechanism for retrieving
additional modifier states. The following dictionary enables authors to
initialize keyboard modifier attributes of the MouseEvent
and KeyboardEvent
interfaces, as well as the additional modifier states
queried via getModifierState()
. The steps for
constructing events using this dictionary are defined in the MouseEvent constructors section.
dictionary :
EventModifierInit UIEventInit {boolean ctrlKey =false ;boolean shiftKey =false ;boolean altKey =false ;boolean metaKey =false ;boolean modifierAltGraph =false ;boolean modifierCapsLock =false ;boolean modifierFn =false ;boolean modifierFnLock =false ;boolean modifierHyper =false ;boolean modifierNumLock =false ;boolean modifierScrollLock =false ;boolean modifierSuper =false ;boolean modifierSymbol =false ;boolean modifierSymbolLock =false ; };
ctrlKey
, of type boolean, defaulting tofalse
-
Initializes the
ctrlKey
attribute of theMouseEvent
orKeyboardEvent
objects totrue
if theControl
key modifier is to be considered active,false
otherwise.When
true
, implementations must also initialize the event object’s key modifier state such that calls to thegetModifierState()
orgetModifierState()
when provided with the parameterControl
must returntrue
. shiftKey
, of type boolean, defaulting tofalse
-
Initializes the
shiftKey
attribute of theMouseEvent
orKeyboardEvent
objects totrue
if theShift
key modifier is to be considered active,false
otherwise.When
true
, implementations must also initialize the event object’s key modifier state such that calls to thegetModifierState()
orgetModifierState()
when provided with the parameterShift
must returntrue
. altKey
, of type boolean, defaulting tofalse
-
Initializes the
altKey
attribute of theMouseEvent
orKeyboardEvent
objects totrue
if theAlt
(alternative) (orOption
) key modifier is to be considered active,false
otherwise.When
true
, implementations must also initialize the event object’s key modifier state such that calls to thegetModifierState()
orgetModifierState()
when provided with the parameterAlt
must returntrue
. metaKey
, of type boolean, defaulting tofalse
-
Initializes the
metaKey
attribute of theMouseEvent
orKeyboardEvent
objects totrue
if theMeta
key modifier is to be considered active,false
otherwise.When
true
, implementations must also initialize the event object’s key modifier state such that calls to thegetModifierState()
orgetModifierState()
when provided with either the parameterMeta
must returntrue
. modifierAltGraph
, of type boolean, defaulting tofalse
- Initializes the event object’s key modifier state such that calls to the
getModifierState()
orgetModifierState()
when provided with the parameterAltGraph
must returntrue
. modifierCapsLock
, of type boolean, defaulting tofalse
- Initializes the event object’s key modifier state such that calls to the
getModifierState()
orgetModifierState()
when provided with the parameterCapsLock
must returntrue
. modifierFn
, of type boolean, defaulting tofalse
- Initializes the event object’s key modifier state such that calls to the
getModifierState()
orgetModifierState()
when provided with the parameterFn
must returntrue
. modifierFnLock
, of type boolean, defaulting tofalse
- Initializes the event object’s key modifier state such that calls to the
getModifierState()
orgetModifierState()
when provided with the parameterFnLock
must returntrue
. modifierHyper
, of type boolean, defaulting tofalse
- Initializes the event object’s key modifier state such that calls to the
getModifierState()
orgetModifierState()
when provided with the parameterHyper
must returntrue
. modifierNumLock
, of type boolean, defaulting tofalse
- Initializes the event object’s key modifier state such that calls to the
getModifierState()
orgetModifierState()
when provided with the parameterNumLock
must returntrue
. modifierScrollLock
, of type boolean, defaulting tofalse
- Initializes the event object’s key modifier state such that calls to the
getModifierState()
orgetModifierState()
when provided with the parameterScrollLock
must returntrue
. modifierSuper
, of type boolean, defaulting tofalse
- Initializes the event object’s key modifier state such that calls to the
getModifierState()
orgetModifierState()
when provided with the parameterSuper
must returntrue
. modifierSymbol
, of type boolean, defaulting tofalse
- Initializes the event object’s key modifier state such that calls to the
getModifierState()
orgetModifierState()
when provided with the parameterSymbol
must returntrue
. modifierSymbolLock
, of type boolean, defaulting tofalse
- Initializes the event object’s key modifier state such that calls to the
getModifierState()
orgetModifierState()
when provided with the parameterSymbolLock
must returntrue
.
3.4.2.1. Constructing Mouse Events
Generally, when a constructor of an Event
interface, or of an interface
inherited from the Event
interface, is invoked, the steps described in [DOM] should be followed. However the MouseEvent
interfaces provide additional dictionary members for
initializing the internal state of the Event
object’s key modifiers:
specifically, the internal state queried for using the getModifierState()
methods. This section supplements the DOM4 steps for intializing a new MouseEvent
object with these optional modifier states.
For the purposes of constructing a MouseEvent
, or
object derived from these objects using the algorithm below, all MouseEvent
, and derived objects have internal key modifier state which can be set and
retrieved using the key modifier names described in the Modifier Keys table in [UIEvents-Key].
The following steps supplement the algorithm defined for constructing events in DOM4:
-
If the
Event
being constructed is aMouseEvent
object or an object that derives from it, and aEventModifierInit
argument was provided to the constructor, then run the following sub-steps:-
For each
EventModifierInit
argument, if the dictionary member begins with the string"modifier"
, then let the key modifier name be the dictionary member’s name excluding the prefix"modifier"
, and set theEvent
object’s internal key modifier state that matches the key modifier name to the corresponding value.
-
3.4.3. MouseEvent Algorithms
3.4.3.1. Native OS Requirements
The algorithms in this section assume that the native platform OS will provide the following:
-
An event when the mouse is moved (handled by handle native mouse move)
-
An event when a mouse button is pressed (handled by handle native mouse down)
-
An event when a mouse button is released (handled by handle native mouse up)
-
A way to identify when a mouse button press should be interpreted as a "click" (handled by handle native mouse click)
-
For example, as a flag or as a separate event
-
If a separate "click" event is fired, then the native OS will fire it immediately after the corresponding "mouse up" event, with no intervening mouse-related events
-
-
A way to identify when a mouse click is a "double click" (handled by handle native mouse double click)
For these events, the OS will be able to provide the following info:
-
The x,y mouse coordinates relative to the native OS desktop
-
The x,y mouse coordinates relative to the UA’s window viewport
-
Which keyboard modifiers are currently being held
3.4.3.2. Global State for MouseEvent
3.4.3.2.1. User Agent-Level State
The UA must maintain the following values that are shared for the entire User Agent.
A mouse button bitmask that tracks the current state of the mouse buttons.
3.4.3.2.2. Window-Level State
The UA must maintain the following values that are shared for the Window.
A last mouse element value (initially undefined) that keeps track
of the last Element
that we sent a MouseEvent to.
A last mouse DOM path value (initially empty) that contains a snapshot
of the ancestors Element
s of the last mouse element when the most recent mouse
event was sent.
3.4.3.3. Internal State for MouseEvent
A MouseEvent
has the following internal flags that are used to track the
state of various modifier keys: shift flag, control flag, alt flag, altgraph flag,
and meta flag.
These flags are set if the corresponding modifier key was pressed at the time
of the mouse event.
3.4.3.4. initialize a MouseEvent
- Input
-
event, the
MouseEvent
to initializeeventType, a DOMString containing the event type
eventTarget, the
EventTarget
of the eventbubbles, true if this event bubbles
cancelable, true if this event is cancelable
- Output
-
None
-
Initialize a UIEvent with event, eventType, eventTarget, bubbles and cancelable.
-
Initialize the following public attributes:
-
Set event.
screenX
= the x-coordinate of the position where the event occurred relative to the origin of the desktop -
Set event.
screenY
= the y-coordinate of the position where the event occurred relative to the origin of the desktop -
Set event.
clientX
= the x-coordinate of the position where the event occurred relative to the origin of the viewport -
Set event.
clientY
= the y-coordinate of the position where the event occurred relative to the origin of the viewport -
Set mouse event modifiers with event
-
Set event.
button
= 0 -
Set event.
buttons
= mouse button bitmask
-
3.4.3.5. set mouse event modifiers
- Input
-
event, the
MouseEvent
to update - Output
-
None
-
Set event’s shift flag if key modifier state includes "Shift", unset it otherwise
-
Set event’s control flag if key modifier state includes "Control", unset it otherwise
-
Set event’s alt flag if key modifier state includes "Alt", unset it otherwise
-
Set event’s altgraph flag if key modifier state includes "AltGraph", unset it otherwise
-
Set event’s meta flag if key modifier state includes "Meta", unset it otherwise
-
Set event.
shiftKey
= true if the event’s shift flag is set, false otherwise -
Set event.
ctrlKey
= true if the event’s control flag is set, false otherwise -
Set event.
altKey
= true if the event’s alt flag or altgraph flag is set, false otherwise -
Set event.
metaKey
= true if the event’s meta flag is set, false otherwise
3.4.3.6. create a cancelable MouseEvent
- Input
-
eventType, a DOMString containing a valid
MouseEvent
typeeventTarget, the
EventTarget
of the event - Output
-
None
-
Let bubbles be "true"
-
Let cancelable be "true"
-
Let event = the result of creating a new event using
MouseEvent
-
Initialize a MouseEvent with event, eventType, eventTarget, bubbles and cancelable.
-
Return event
3.4.3.7. create a non-cancelable MouseEvent
- Input
-
eventType, a DOMString containing a valid
MouseEvent
typeeventTarget, the
EventTarget
of the event - Output
-
None
-
Let bubbles be "false"
-
Let cancelable be "false"
-
Let event = the result of creating a new event using
MouseEvent
-
Initialize a MouseEvent with event, eventType, eventTarget, bubbles and cancelable.
-
Return event
3.4.3.8. calculate MouseEvent button attribute
- Input
-
mbutton, an ID that identifies a mouse button
- Output
-
A button ID suitable for storing in the
MouseEvent
'sbutton
attribute
-
If mbutton is the primary mouse button, then return 0
-
If mbutton is the auxiliary (middle) mouse button, then return 1
-
If mbutton is the secondary mouse button, then return 2
-
If mbutton is the X1 (back) button, then return 3
-
If mbutton is the X2 (forward) button, then return 4
3.4.3.9. set MouseEvent attributes from native
- Input
-
event, the
MouseEvent
to initializenative, the native mouse event
- Output
-
None
TODO
-
If event.
type
is one of [ mousedown, mouseup ], then-
Let mbutton be an ID from native that identifies which mouse button was pressed
-
Set event.
button
= calculate MouseEvent button attribute with mbutton
-
3.4.3.10. handle native mouse down
- Input
-
native, the native mousedown
- Output
-
None
-
Let mbutton be an ID from native that identifies which mouse button was pressed
-
Update the mouse button bitmask as follows:
-
If mbutton is the primary mouse button, then set the 0x01 bit
-
If mbutton is the secondary mouse button, then set the 0x02 bit
-
If mbutton is the auxiliary (middle) mouse button, then set the 0x04 bit
Other buttons can be added starting with 0x08
-
-
Let target = hit test with viewport-relative coordinates from native
-
Let event = create a cancelable MouseEvent with "mousedown", target
-
Set MouseEvent attributes from native with native
-
Maybe send pointerdown event with event
-
Let result = dispatch event at target
-
If result is true and target is a focusable area that is click focusable, then
-
Run the focusing steps at target
-
-
if mbutton is the secondary mouse button, then
-
Maybe show context menu with native, target
-
3.4.3.11. handle native mouse up
- Input
-
native, the native mouseup
- Output
-
None
Other mouse events can occur between the mousedown and mouseup.
-
Let mbutton be an ID from native that identifies which mouse button was pressed
-
Update the mouse button bitmask as follows:
-
If mbutton is the primary mouse button, then clear the 0x01 bit
-
If mbutton is the secondary mouse button, then clear the 0x02 bit
-
If mbutton is the auxiliary (middle) mouse button, then clear the 0x04 bit
-
-
Let target = hit test with viewport-relative coordinates from native
-
Let event = create a cancelable MouseEvent with "mouseup", target
-
Set MouseEvent attributes from native with native
-
Maybe send pointerup event with event
-
dispatch event at target
3.4.3.12. handle native mouse click
- Input
-
native, the native mouse click
- Output
-
None
The platform should call this immediately after handle native mouse up for mouseups that generate clicks.
-
Let target = hit test with viewport-relative coordinates from native
-
Send click event with native and target.
3.4.3.13. send click event
- Input
-
native, the native mousedown
target, the
EventTarget
of the event - Output
-
None
-
Let mbutton = 1 (primary mouse button by default)
-
If native is valid, then
-
Let mbutton be an ID from native that identifies which mouse button was pressed
-
-
Set eventType = "click" if mbutton is the primary mouse button, otherwise "auxclick"
-
Let event = create a PointerEvent with eventType and target
-
If native is valid, then
-
Set MouseEvent attributes from native with event, native
-
If event.
screenX
is not an integer value, then round it. -
If event.
screenY
is not an integer value, then round it.
-
-
dispatch event at target
See pointerevents/100 for info about browsers using PointerEvents and rounded coordinates.
Any "default action" is handled during dispatch by triggering the activation behavior algorithm for the target. So there is no need for handle that here. However, need to verify that the existing spec handles disabled/css-pointer-events/inert/...
To handle `HTMLelement.click()`, call this algorithm with native = null and target = `HTMLelement`.
To handle keyboard-initiated clicks, call this algorithm with native = null and target = currently focused element.
3.4.3.14. handle native mouse double click
- Input
-
native, the native mouse double click
- Output
-
None
This should be called immediately after handle native mouse click for mouse clicks that generate double clicks.
-
Let mbutton be an ID from native that identifies which mouse button was pressed
-
If mbutton is not the primary mouse button, then return
-
Let target = hit test with viewport-relative coordinates from native
-
Let event = create a PointerEvent with "dblclick" and target
-
Set MouseEvent attributes from native with event, native
-
If event.
screenX
is not an integer value, then round it. -
If event.
screenY
is not an integer value, then round it. -
dispatch event at target
3.4.3.15. handle native mouse move
- Input
-
native, the native mouse move
- Output
-
None
This algorithm makes assumptions about the dispatch of PointerEvents because they are not currently specified explicitly. Once pointerevents/285 is resolved this may need to be updated.
-
Let target = hit test with viewport-relative coordinates from native
-
Let targetDomPath = calculate DOM path
-
Generate events for leaving the current element:
-
If last mouse element is defined and not equal to target, then
-
Let mouseout = create a cancelable MouseEvent with "mouseout" and last mouse element
TODO: Set mouseout attributes from native. +CSSOM attributes
-
Maybe send pointerout event with mouseout
-
Dispatch mouseout at target
Verify behavior when canceled (appears to have no effect).
-
Let leaveElements be a copy of last mouse DOM path with all elements common to targetDomPath removed.
-
For each element in leaveElements, do
Handle case where element has been deleted. Also case where it has been moved: Should the DOM mutation have triggered a mouseleave event? Should we sent it now? Should it be dropped? Need to verify what current browsers do.
-
Let mouseleave = create a non-cancelable MouseEvent with "mouseleave" and element
-
Set mouseleave.
composed
= falseCheck compat: Value of event.composed. Spec says false. Chrome/Linux = true. Firefox/Linux = false.
-
Maybe send pointerleave event with mouseleave
-
Let result = dispatch mouseleave at element
-
-
-
-
Generate events for entering the new element:
-
If target is not last mouse element, then
-
Let mouseover = create a cancelable MouseEvent with "mouseover" and target
TODO: Set mouseout attributes from native. +CSSOM attributes
-
Maybe send pointerover event with mouseover
-
Dispatch mouseout at target
Need to verify behavior when canceled (appears to have no effect).
-
Let enterElements be a copy of targetDomPath with all elements common to last mouse DOM path removed.
-
For each element in enterElements, do
Handle case where element has been deleted or moved.
-
Let mouseenter = create a non-cancelable MouseEvent with "mouseenter" and element
-
Set mouseenter.
composed
= falseCheck compat: Value of event.composed. Spec says false. Chrome/Linux = true. Firefox/Linux = false.
-
Maybe send pointerenter event with mouseenter
Check compat for shadow DOM elements. Chrome/Linux fires this event at the element and the shadow root.
-
Let result = dispatch mouseenter at element
-
-
Set last mouse element to target
-
Set last mouse DOM path to targetDomPath
-
-
-
Let mousemove = create a cancelable MouseEvent with "mousemove" and element
-
Maybe send pointermove event with mousemove
-
Dispatch mousemove at element
3.4.3.16. maybe show context menu
- Input
-
native, the native mousedown or pointer event
target, the
EventTarget
of the event - Output
-
None
-
Let menuevent = create a PointerEvent with "contextmenu", target
-
If native is valid, then
-
Set MouseEvent attributes from native with native
-
-
Let result = dispatch menuevent at target
-
If result is true, then show the UA context menu
-
To handle a context menu triggered by the keyboard, call this algorithm with native = null and target = currently focused element.
3.4.4. Mouse Event Order
Certain mouse events defined in this specification MUST occur in a set order relative to one another. The following shows the event sequence that MUST occur when a pointing device’s cursor is moved over an element:
Event Type | Element | Notes | |
---|---|---|---|
1 | mousemove
| ||
Pointing device is moved into element A... | |||
2 | mouseover
| A | |
3 | mouseenter
| A | |
4 | mousemove
| A | Multiple mousemove events
|
Pointing device is moved out of element A... | |||
5 | mouseout
| A | |
6 | mouseleave
| A |
When a pointing device is moved into an element A, and then into a nested element B and then back out again, the following sequence of events MUST occur:
Event Type | Element | Notes | |
---|---|---|---|
1 | mousemove
| ||
Pointing device is moved into element A... | |||
2 | mouseover
| A | |
3 | mouseenter
| A | |
4 | mousemove
| A | Multiple mousemove events
|
Pointing device is moved into nested element B... | |||
5 | mouseout
| A | |
6 | mouseover
| B | |
7 | mouseenter
| B | |
8 | mousemove
| B | Multiple mousemove events
|
Pointing device is moved from element B into A... | |||
9 | mouseout
| B | |
10 | mouseleave
| B | |
11 | mouseover
| A | |
12 | mousemove
| A | Multiple mousemove events
|
Pointing device is moved out of element A... | |||
13 | mouseout
| A | |
14 | mouseleave
| A |
Sometimes elements can be visually overlapped using CSS. In the following example, three elements labeled A, B, and C all have the same dimensions and absolute position on a web page. Element C is a child of B, and B is a child of A in the DOM:
When the pointing device is moved from outside the element stack to the element labeled C and then moved out again, the following series of events MUST occur:
Event Type | Element | Notes | |
---|---|---|---|
1 | mousemove
| ||
Pointing device is moved into element C, the topmost element in the stack | |||
2 | mouseover
| C | |
3 | mouseenter
| A | |
4 | mouseenter
| B | |
5 | mouseenter
| C | |
6 | mousemove
| C | Multiple mousemove events
|
Pointing device is moved out of element C... | |||
7 | mouseout
| C | |
8 | mouseleave
| C | |
9 | mouseleave
| B | |
10 | mouseleave
| A |
The mouseover
/mouseout
events are only fired once, while mouseenter
/mouseleave
events are fired three times (once
to each element).
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:
Event Type | Notes | |
---|---|---|
1 | mousedown
| |
2 | mousemove
| OPTIONAL, multiple events, some limits |
3 | mouseup
| |
4 | click
| |
5 | mousemove
| OPTIONAL, multiple events, some limits |
6 | mousedown
| |
7 | mousemove
| OPTIONAL, multiple events, some limits |
8 | mouseup
| |
9 | click
| |
10 | dblclick
|
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 inclusive ancestor when the
associated mousedown
and mouseup
event targets are
different.
If a mousedown
event was targeted at an HTML document’s body
element, and the corresponding mouseup
event was targeted at
the root element, then the click
event will be dispatched
to the root element, since it is the nearest common inclusive
ancestor.
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.
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.
3.4.5. Mouse Event Types
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.
3.4.5.1. auxclick
Type | auxclick
|
---|---|
Interface | PointerEvent
|
Sync / Async | Sync |
Bubbles | Yes |
Trusted Targets | Element
|
Cancelable | Yes |
Composed | Yes |
Default action | Varies |
Context (trusted events) |
|
The auxclick
event type MUST be dispatched on the topmost
event target indicated by the pointer, when the user presses
down and releases the non-primary 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 auxclick
event should only be fired for the non-primary pointer
buttons (i.e., when button
value is not 0
, buttons
value is greater than 1
). The primary button
(like the left button on a standard mouse) MUST NOT fire auxclick
events. See click
for a corresponding event that
is associated with the primary button.
The auxclick
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 auxclick
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 default action of the auxclick
event type varies
based on the event target of the event and the value of the button
or buttons
attributes. Typical default actions of the auxclick
event type are as follows:
-
If the event target has associated activation behavior, the default action MUST be to execute that activation behavior.
Receiving and handling auxclick for the middle button.
myLink.addEventListener("auxclick", function(e) {
if (e.button === 1) {
// This would prevent the default behavior which is for example
// opening a new tab when middle clicking on a link.
e.preventDefault();
// Do something else to handle middle button click like taking
// care of opening link or non-link buttons in new tabs in a way
// that fits the app. Other actions like closing a tab in a tab-strip
// which should be done on the click action can be done here too.
}
});
In the case of right button, the auxclick
event is dispatched after
any contextmenu
event. Note that some user agents swallow all input
events while a context menu is being displayed, so auxclick may not be
available to applications in such scenarios.
See this example for more clarification.
Receiving and handling auxclick for the right button
myDiv.addEventListener("contextmenu", function(e) {
// This call makes sure no context menu is shown
// to interfere with page receiving the events.
e.preventDefault();
});
myDiv.addEventListener("auxclick", function(e) {
if (e.button === 2) {
// Do something else to handle right button click like opening a
// customized context menu inside the app.
}
});
3.4.5.2. click
Type | click
|
---|---|
Interface | PointerEvent
|
Sync / Async | Sync |
Bubbles | Yes |
Trusted Targets | Element
|
Cancelable | Yes |
Composed | Yes |
Default action | Varies |
Context (trusted events) |
|
The click
event type MUST be dispatched on the topmost
event target indicated by the pointer, when the user presses
down and releases the primary 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 should only be fired for the primary pointer
button (i.e., when button
value is 0
, buttons
value is 1
). Secondary buttons
(like the middle or right button on a standard mouse) MUST NOT fire click
events. See auxclick
for a corresponding event that
is associated with the non-primary buttons.
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.
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. Note that 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.
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 button
or buttons
attributes. Typical default actions of the click
event type are as follows:
-
If the event target has associated activation behavior, the default action MUST be to execute that activation behavior.
-
If the event target is focusable, the default action MUST be to give that element document focus.
3.4.5.3. contextmenu
Type | contextmenu
|
---|---|
Interface | PointerEvent
|
Sync / Async | Sync |
Bubbles | Yes |
Trusted Targets | Element
|
Cancelable | Yes |
Composed | Yes |
Default action | Invoke a context menu if supported. |
Context (trusted events) |
|
A user agent MUST dispatch this event before invoking a context menu.
When the contextmenu
event is triggered by right mouse button, the contextmenu
event MUST be dispatched after the mousedown
event.
Depending on the platform, the contextmenu
event may be dispatched
before or after the mouseup
event.
3.4.5.4. dblclick
Type | dblclick
|
---|---|
Interface | MouseEvent
|
Sync / Async | Sync |
Bubbles | Yes |
Trusted Targets | Element
|
Cancelable | Yes |
Composed | Yes |
Default action | None |
Context (trusted events) |
|
A user agent MUST dispatch this event when the primary button
of a pointing device 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.
As with the click
event, the dblclick
event should
only be fired for the primary pointer button. Secondary buttons MUST
NOT fire dblclick
events.
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 button
or buttons
attributes. The typical default actions of the dblclick
event type match those
of the click
event type.
3.4.5.5. mousedown
Type | mousedown
|
---|---|
Interface | MouseEvent
|
Sync / Async | Sync |
Bubbles | Yes |
Trusted Targets | Element
|
Cancelable | Yes |
Composed | 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 (trusted events) |
|
A user agent MUST dispatch this event when a pointing device button is pressed over an element.
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.
3.4.5.6. mouseenter
Type | mouseenter
|
---|---|
Interface | MouseEvent
|
Sync / Async | Sync |
Bubbles | No |
Trusted Targets | Element
|
Cancelable | No |
Composed | No |
Default action | None |
Context (trusted events) |
|
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. A user agent MUST also dispatch this event when the
element or one of its descendants moves to be underneath the primary
pointing device. 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.
There are similarities between this event type and the CSS :hover
pseudo-class [CSS2].
See also the mouseleave
event type.
3.4.5.7. mouseleave
Type | mouseleave
|
---|---|
Interface | MouseEvent
|
Sync / Async | Sync |
Bubbles | No |
Trusted Targets | Element
|
Cancelable | No |
Composed | No |
Default action | None |
Context (trusted events) |
|
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. A user agent MUST also dispatch this event
when the element or one of its descendants moves to be no longer underneath
the primary pointing device. 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.
There are similarities between this event type and the CSS :hover
pseudo-class [CSS2].
See also the mouseenter
event type.
3.4.5.8. mousemove
Type | mousemove
|
---|---|
Interface | MouseEvent
|
Sync / Async | Sync |
Bubbles | Yes |
Trusted Targets | Element
|
Cancelable | Yes |
Composed | Yes |
Default action | None |
Context (trusted events) |
|
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.
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.
This event was formerly specified to be non-cancelable in DOM Level 2 Events, but was changed to reflect existing interoperability between user agents.
3.4.5.9. mouseout
Type | mouseout
|
---|---|
Interface | MouseEvent
|
Sync / Async | Sync |
Bubbles | Yes |
Trusted Targets | Element
|
Cancelable | Yes |
Composed | Yes |
Default action | None |
Context (trusted events) |
|
A user agent MUST dispatch this event when a pointing device
is moved off of the boundaries of an element or when the element is
moved to be no longer underneath the primary pointing device.
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.
See also the mouseover
event type.
3.4.5.10. mouseover
Type | mouseover
|
---|---|
Interface | MouseEvent
|
Sync / Async | Sync |
Bubbles | Yes |
Trusted Targets | Element
|
Cancelable | Yes |
Composed | Yes |
Default action | None |
Context (trusted events) |
|
A user agent MUST dispatch this event when a pointing device
is moved onto the boundaries of an element or when the element is
moved to be underneath the primary pointing device.
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.
See also the mouseout
event type.
3.4.5.11. mouseup
Type | mouseup
|
---|---|
Interface | MouseEvent
|
Sync / Async | Sync |
Bubbles | Yes |
Trusted Targets | Element
|
Cancelable | Yes |
Composed | Yes |
Default action | None |
Context (trusted events) |
|
A user agent MUST dispatch this event when a pointing device button is released over an element.
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.
3.5. Wheel Events
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.
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.
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.
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).
A user agent MUST create a wheel event transaction when the first wheel event is fired, so that all subsequent wheel events within a implementation-specific amount of time can be targetted at the same element. A wheel event transaction is series of wheel events that are associated with a single user gesture. The wheel event transaction MUST have an associated event target that is the topmost event target at the time the first wheel event occurs in the group.
If a series of wheel events targetted in a scrollable element start above a child element, later events for the same user gesture may occur over the child element.
3.5.1. Interface WheelEvent
Introduced in this specification
The WheelEvent
interface provides specific contextual information
associated with wheel
events.
To create an instance of the WheelEvent
interface, use the WheelEvent
constructor,
passing an optional WheelEventInit
dictionary.
3.5.1.1. WheelEvent
[Exposed =Window ]interface :
WheelEvent MouseEvent {(
constructor DOMString ,
type optional WheelEventInit = {}); // DeltaModeCode
eventInitDict const unsigned long DOM_DELTA_PIXEL = 0x00;const unsigned long DOM_DELTA_LINE = 0x01;const unsigned long DOM_DELTA_PAGE = 0x02;readonly attribute double deltaX ;readonly attribute double deltaY ;readonly attribute double deltaZ ;readonly attribute unsigned long deltaMode ; };
DOM_DELTA_PIXEL
- The units of measurement for the delta MUST be pixels. This is the most typical case in most operating system and implementation configurations.
DOM_DELTA_LINE
- The units of measurement for the delta MUST be individual lines of text. This is the case for many form controls.
DOM_DELTA_PAGE
- The units of measurement for the delta MUST be pages, either defined as a single screen or as a demarcated page.
deltaX
, of type double, readonly-
In 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.0
. deltaY
, of type double, readonly-
In 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.0
. deltaZ
, of type double, readonly-
In 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.0
. deltaMode
, of type unsigned long, readonly-
The
deltaMode
attribute contains an indication of the units of measurement for the delta values. The default value isDOM_DELTA_PIXEL
(pixels).This attribute MUST be set to one of the DOM_DELTA constants to indicate the units of measurement for the delta values. The precise measurement is specific to device, operating system, and application configurations.
The un-initialized value of this attribute MUST be
0
.
3.5.1.2. WheelEventInit
dictionary :
WheelEventInit MouseEventInit {double deltaX = 0.0;double deltaY = 0.0;double deltaZ = 0.0;unsigned long deltaMode = 0; };
deltaX
, of type double, defaulting to0.0
- See
deltaZ
attribute. deltaY
, of type double, defaulting to0.0
- See
deltaZ
attribute. deltaZ
, of type double, defaulting to0.0
- Initializes the
deltaZ
attribute of theWheelEvent
object. Relative positive values for this attribute (as well as thedeltaX
anddeltaY
attributes) are given by a right-hand coordinate system where the 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. Negative relative values are in the respective opposite directions. deltaMode
, of type unsigned long, defaulting to0
- Initializes the
deltaMode
attribute on theWheelEvent
object to the enumerated values 0, 1, or 2, which represent the amount of pixels scrolled (DOM_DELTA_PIXEL
), lines scrolled (DOM_DELTA_LINE
), or pages scrolled (DOM_DELTA_PAGE
) if the rotation of the wheel would have resulted in scrolling.
3.5.2. Wheel Event Types
3.5.2.1. wheel
Type | wheel
|
---|---|
Interface | WheelEvent
|
Sync / Async | Async |
Bubbles | Yes |
Trusted Targets | Element
|
Cancelable | Varies |
Composed | Yes |
Default action | Scroll (or zoom) the document |
Context (trusted events) |
|
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).
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.
3.5.2.2. cancelability of wheel events
Calling preventDefault
on a wheel event can prevent
or otherwise interrupt scrolling. For maximum scroll performance, a
user agent may not wait for each wheel event associated with the scroll
to be processed to see if it will be canceled. In such cases the user
agent should generate wheel
events whose cancelable
property is false
, indicating that preventDefault
cannot be used to prevent or interrupt
scrolling. Otherwise cancelable
will be true
.
In particular, a user agent should generate only uncancelable wheel
events when it observes
that there are no non-passive listeners for the event.
3.6. Input Events
Input events are sent as notifications whenever the DOM is being updated (or about to be updated) as a direct result of a user action (e.g., keyboard input in an editable region, deleting or formatting text, ...).
3.6.1. Interface InputEvent
3.6.1.1. InputEvent
Introduced in DOM Level 3
[Exposed =Window ]interface :
InputEvent UIEvent {(
constructor DOMString ,
type optional InputEventInit = {});
eventInitDict readonly attribute USVString ?data ;readonly attribute boolean isComposing ;readonly attribute DOMString inputType ; };
data
, of type USVString, readonly, nullable-
data
holds the value of the characters generated by an input method. This MAY be a single Unicode character or a non-empty sequence of Unicode characters [Unicode]. Characters SHOULD be normalized as defined by the Unicode normalization form NFC, defined in [UAX15]. This attribute MAY contain the empty string.The un-initialized value of this attribute MUST be
null
. isComposing
, of type boolean, readonly-
true
if the input event occurs as part of a composition session, i.e., after acompositionstart
event and before the correspondingcompositionend
event.The un-initialized value of this attribute MUST be
false
. inputType
, of type DOMString, readonly-
inputType
contains a string that identifies the type of input associated with the event.For a list of valid values for this attribute, refer to the [Input-Events] specification.
The un-initialized value of this attribute MUST be the empty string
""
.
3.6.1.2. InputEventInit
dictionary :
InputEventInit UIEventInit {DOMString ?data =null ;boolean isComposing =false ;DOMString inputType = ""; };
data
, of type DOMString, nullable, defaulting tonull
- Initializes the
data
attribute of the InputEvent object. isComposing
, of type boolean, defaulting tofalse
- Initializes the
isComposing
attribute of the InputEvent object. inputType
, of type DOMString, defaulting to""
- Initializes the
inputType
attribute of the InputEvent object.
3.6.2. Input Event Order
The input events defined in this specification MUST occur in a set order relative to one another.
Event Type | Notes | |
---|---|---|
1 | beforeinput
| |
DOM element is updated | ||
2 | input
|
3.6.3. Input Event Types
3.6.3.1. beforeinput
Type | beforeinput
|
---|---|
Interface | InputEvent
|
Sync / Async | Sync |
Bubbles | Yes |
Trusted Targets | Element (specifically: control types such as HTMLInputElement , etc.) or any Element with contenteditable attribute enabled
|
Cancelable | Yes |
Composed | Yes |
Default action | Update the DOM element |
Context (trusted events) |
|
A user agent MUST dispatch this event when the DOM is about to be updated.
3.6.3.2. input
Type | input
|
---|---|
Interface | InputEvent
|
Sync / Async | Sync |
Bubbles | Yes |
Trusted Targets | Element (specifically: control types such as HTMLInputElement , etc.) or any Element with contenteditable attribute enabled
|
Cancelable | No |
Composed | Yes |
Default action | None |
Context (trusted events) |
|
A user agent MUST dispatch this event immediately after the DOM has been updated.
3.7. Keyboard Events
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.
Keyboard events are only one modality of providing textual input. For
editing scenarios, consider also using the InputEvent
as an alternate to
(or in addition to) keyboard events.
3.7.1. Interface KeyboardEvent
Introduced in this specification
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: ctrlKey
, shiftKey
, altKey
, metaKey
. These attributes are equivalent to using the
method getModifierState()
with Control
, Shift
, Alt
, or Meta
respectively.
To create an instance of the KeyboardEvent
interface, use the KeyboardEvent
constructor, passing an optional KeyboardEventInit
dictionary.
3.7.1.1. KeyboardEvent
[Exposed =Window ]interface :
KeyboardEvent UIEvent {(
constructor DOMString ,
type optional KeyboardEventInit = {}); // KeyLocationCode
eventInitDict 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;readonly attribute DOMString key ;readonly attribute DOMString code ;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 boolean isComposing ;boolean getModifierState (DOMString ); };
keyArg
DOM_KEY_LOCATION_STANDARD
-
The key activation MUST NOT be distinguished as the left or
right version of the key, and (other than the
NumLock
key) did not originate from the numeric keypad (or did not originate with a virtual key corresponding to the numeric keypad).The
Q
key on a PC 101 Key US keyboard.
TheNumLock
key on a PC 101 Key US keyboard.
The1
key on a PC 101 Key US keyboard located in the main section of the keyboard. DOM_KEY_LOCATION_LEFT
- The key activated originated from the left key location (when there is more than one possible location for this key).
DOM_KEY_LOCATION_RIGHT
- The key activation originated from the right key location (when there is more than one possible location for this key).
DOM_KEY_LOCATION_NUMPAD
-
The key activation originated on the numeric keypad or with a
virtual key corresponding to the numeric keypad (when there is
more than one possible location for this key). Note that the
NumLock
key should always be encoded with alocation
ofDOM_KEY_LOCATION_STANDARD
.The
1
key on a PC 101 Key US keyboard located on the numeric pad. key
, of type DOMString, readonly-
key
holds a key attribute value corresponding to the key pressed.The
key
attribute is not related to the legacykeyCode
attribute and does not have the same set of values.The un-initialized value of this attribute MUST be
""
(the empty string). code
, of type DOMString, readonly-
code
holds a string that identifies the physical key being pressed. The value is not affected by the current keyboard layout or modifier state, so a particular key will always return the same value.The un-initialized value of this attribute MUST be
""
(the empty string). location
, of type unsigned long, readonly-
The
location
attribute contains an indication of the logical location of the key on the device.This attribute MUST be set to one of the DOM_KEY_LOCATION constants to indicate the location of a key on the device.
If a user agent allows keys to be remapped, then the
location
value for a remapped key MUST be set to a value which is appropriate for the new key. For example, if the"ControlLeft"
key is mapped to the"KeyQ"
key, then thelocation
attribute MUST be set toDOM_KEY_LOCATION_STANDARD
. Conversely, if the"KeyQ"
key is remapped to one of theControl
keys, then thelocation
attribute MUST be set to eitherDOM_KEY_LOCATION_LEFT
orDOM_KEY_LOCATION_RIGHT
.The un-initialized value of this attribute MUST be
0
. ctrlKey
, of type boolean, readonly-
true
if theControl
(control) key modifier was active.The un-initialized value of this attribute MUST be
false
. shiftKey
, of type boolean, readonly-
true
if the shift (Shift
) key modifier was active.The un-initialized value of this attribute MUST be
false
. altKey
, of type boolean, readonly-
true
if theAlt
(alternative) (or"Option"
) key modifier was active.The un-initialized value of this attribute MUST be
false
. metaKey
, of type boolean, readonly-
true
if the meta (Meta
) key modifier was active.The
"Command"
("⌘"
) key modifier on Macintosh systems is represented using this key modifier.The un-initialized value of this attribute MUST be
false
. repeat
, of type boolean, readonly-
true
if the key has been pressed in a sustained manner. Holding down a key MUST result in the repeating the eventskeydown
,beforeinput
,input
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 arepeat
attribute value oftrue
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
. isComposing
, of type boolean, readonly-
true
if the key event occurs as part of a composition session, i.e., after acompositionstart
event and before the correspondingcompositionend
event.The un-initialized value of this attribute MUST be
false
. getModifierState(keyArg)
-
Queries the state of a modifier using a key value.
Returns
true
if it is a modifier key and the modifier is activated,false
otherwise.- DOMString keyArg
-
A modifier key value. Valid modifier keys are defined
in the Modifier Keys table in [UIEvents-Key].
If an application wishes to distinguish between right and left modifiers, this information could be deduced using keyboard events and
location
.
3.7.1.2. KeyboardEventInit
dictionary :
KeyboardEventInit EventModifierInit {DOMString key = "";DOMString code = "";unsigned long location = 0;boolean repeat =false ;boolean isComposing =false ; };
key
, of type DOMString, defaulting to""
- Initializes the
key
attribute of the KeyboardEvent object to the unicode character string representing the meaning of a key after taking into account all keyboard modifiers (such as shift-state). This value is the final effective value of the key. If the key is not a printable character, then it should be one of the key values defined in [UIEvents-Key]. code
, of type DOMString, defaulting to""
- Initializes the
code
attribute of the KeyboardEvent object to the unicode character string representing the key that was pressed, ignoring any keyboard modifications such as keyboard layout. This value should be one of the code values defined in [UIEvents-Code]. location
, of type unsigned long, defaulting to0
-
Initializes the
location
attribute of the KeyboardEvent object to one of the following location numerical constants:-
DOM_KEY_LOCATION_STANDARD
(numerical value 0) -
DOM_KEY_LOCATION_LEFT
(numerical value 1) -
DOM_KEY_LOCATION_RIGHT
(numerical value 2) -
DOM_KEY_LOCATION_NUMPAD
(numerical value 3)
-
repeat
, of type boolean, defaulting tofalse
- Initializes the
repeat
attribute of the KeyboardEvent object. This attribute should be set totrue
if the the current KeyboardEvent is considered part of a repeating sequence of similar events caused by the long depression of any single key,false
otherwise. isComposing
, of type boolean, defaulting tofalse
- Initializes the
isComposing
attribute of the KeyboardEvent object. This attribute should be set totrue
if the event being constructed occurs as part of a composition sequence,false
otherwise.
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. This specification does not define
values for either keyCode
or charCode
, or behavior
for charCode
. In conforming UI Events implementations, content
authors can instead use key
and code
.
For more information, see the informative appendix on Legacy key attributes.
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.
In some implementations or system configurations, some key events, or their values, might be suppressed by the IME in use.
3.7.2. Keyboard Event Key Location
The location
attribute can be used to disambiguate
between key
values that can be generated by different
physical keys on the keyboard, for example, the left and right Shift
key or the physical arrow keys vs. the numpad arrow keys
(when NumLock
is off).
The following table defines the valid location
values
for the special keys that have more than one location on the keyboard:
KeyboardEvent . key
| Valid location values
|
---|---|
"Shift" , "Control" , "Alt" , "Meta"
| DOM_KEY_LOCATION_LEFT , DOM_KEY_LOCATION_RIGHT
|
"ArrowDown" , "ArrowLeft" , "ArrowRight" , "ArrowUp"
| DOM_KEY_LOCATION_STANDARD , DOM_KEY_LOCATION_NUMPAD
|
"End" , "Home" , "PageDown" , "PageUp"
| DOM_KEY_LOCATION_STANDARD , DOM_KEY_LOCATION_NUMPAD
|
"0" , "1" , "2" , "2" , "4" , "5" , "6" , "7" , "8" , "9" , "." , "Enter" , "+" , "-" , "*" , "/"
| DOM_KEY_LOCATION_STANDARD , DOM_KEY_LOCATION_NUMPAD
|
For all other keys not listed in this table, the location
attribute MUST always be set to DOM_KEY_LOCATION_STANDARD
.
3.7.3. KeyboardEvent Algorithms
3.7.3.1. Global State for KeyboardEvent
3.7.3.1.1. User Agent-Level State
The UA must maintain the following values that are shared for the entire User Agent.
A key modifier state (initially empty) that keeps track of the current state of each modifier key available on the system.
3.7.4. Keyboard Event Order
The keyboard events defined in this specification occur in a set order relative to one another, for any given key:
Event Type | Notes | |
---|---|---|
1 | keydown
| |
2 | beforeinput
| (only for keys which produce a character value) |
Any default actions related to this key, such as inserting a character in to the DOM. | ||
3 | input
| (only for keys which have updated the DOM) |
Any events as a result of the key being held for a sustained period (see below). | ||
4 | keyup
|
If the key is depressed for a sustained period, the following events MAY repeat at an environment-dependent rate:
Event Type | Notes | |
---|---|---|
1 | keydown
| (with repeat attribute set to true )
|
2 | beforeinput
| (only for keys which produce a character value) |
Any default actions related to this key, such as inserting a character in to the DOM. | ||
3 | input
| (only for keys which have updated the DOM) |
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 an accelerator
key or trigger of some other behavior. If no suitable element is in
focus, the event target will be the HTML body element if
available, otherwise the root element.
The event target might change between different key events. For
example, a keydown
event for the Tab
key will likely have
a different event target than the keyup
event on the same
keystroke.
3.7.5. Keyboard Event Types
3.7.5.1. keydown
Type | keydown
|
---|---|
Interface | KeyboardEvent
|
Sync / Async | Sync |
Bubbles | Yes |
Trusted Targets | Element
|
Cancelable | Yes |
Composed | Yes |
Default action | Varies: beforeinput and input events; launch text composition system; blur and focus events; keypress event (if supported); activation behavior; other event
|
Context (trusted events) |
|
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 beforeinput
, input
, and keyup
events associated
with the same key.
The default action of the keydown
event depends upon the key:
-
If the key is associated with a character, the default action MUST be to dispatch a
beforeinput
event followed by aninput
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 set ofbeforeinput
/input
events for each character -
If the key is associated with a text composition system, the default action MUST be to launch that system
-
If the key is the
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 -
If the key is the
Enter
orclick
event, and aDOMActivate
event if that event type is supported by the user agent.
If this event is canceled, the associated event types MUST NOT be dispatched, and the associated actions MUST NOT be performed.
The keydown
and keyup
events are traditionally
associated with detecting any key, not just those which produce a character value.
3.7.5.2. keyup
Type | keyup
|
---|---|
Interface | KeyboardEvent
|
Sync / Async | Sync |
Bubbles | Yes |
Trusted Targets | Element
|
Cancelable | Yes |
Composed | Yes |
Default action | None |
Context (trusted events) |
|
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
, beforeinput
, and input
events
associated with the same key.
The keydown
and keyup
events are traditionally
associated with detecting any key, not just those which produce a character value.
3.8. Composition Events
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 § 4 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.
3.8.1. Interface CompositionEvent
Introduced in this specification
The CompositionEvent
interface provides specific contextual
information associated with Composition Events.
To create an instance of the