UI Events

W3C Working Draft,

More details about this document
This version:
https://www.w3.org/TR/2024/WD-uievents-20240907/
Latest published version:
https://www.w3.org/TR/uievents/
Editor's Draft:
https://w3c.github.io/uievents/
Previous Versions:
History:
https://www.w3.org/standards/history/uievents/
Feedback:
GitHub
Inline In Spec
Editors:
(Google)
(Microsoft)
Former Editor:
Doug Schepers (Mar 2008 - May 2011)
Tests:
web-platform-tests uievents/ (ongoing work)

Abstract

This specification defines UI Events which extend the DOM Event objects defined in [DOM]. UI Events are those typically implemented by visual user agents for handling user interaction such as mouse and keyboard input.

Status of this document

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

This document was published by the Web Applications Working Group as a Working Draft. This document is intended to become a W3C Recommendation.

This document was published by the Web Applications Working Group as a Working Draft using the Recommendation track. Feedback and comments on this specification are welcome. Please use GitHub issues Historical discussions can be found in the public-webapps@w3.org archives.

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

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

This document is governed by the 03 November 2023 W3C Process Document.

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:

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:

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 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.

Graphical representation of inheritance of interfaces defined by this specification
Graphical representation of inheritance of interfaces defined by 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 the Window 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 detail = 0;
};
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 initialize

eventType, a DOMString containing the event type

eventTarget, the EventTarget of the event

bubbles, true if this event bubbles

cancelable, true if this event is cancelable

Output

None

  1. Initialize the base Event attributes:

    1. Initialize an Event with event, eventType, bubbles and cancelable

    2. Set event.target = eventTarget

  2. Initialize the following public attributes:

    1. Set event.view = the eventTarget’s node document’s Window object

    2. Set event.detail = 0

  3. Initialize the following historical attributes:

    1. Set event.which = 0 (used by both MouseEvent and KeyboardEvent)

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 be null.

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 a focus or focusin event) or the element gaining focus (in the case of a blur or focusout 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 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's ctrlKey attribute.

The un-initialized value of this attribute MUST be false.

shiftKey, of type boolean, readonly
Refer to the KeyboardEvent's shiftKey attribute.

The un-initialized value of this attribute MUST be false.

altKey, of type boolean, readonly
Refer to the KeyboardEvent's altKey attribute.

The un-initialized value of this attribute MUST be false.

metaKey, of type boolean, readonly
Refer to the KeyboardEvent's metaKey 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 than 0 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 value 0 as the left button, but rather as the un-initialized value.

Some default actions related to events such as mousedown and mouseup depend on the specific mouse button in use.

The un-initialized value of this attribute MUST be 0.

buttons, of type unsigned short, 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 the button attribute are very different. The value of button is assumed to be valid during mousedown / mouseup event handlers, whereas the buttons attribute reflects the state of the mouse’s buttons for any trusted MouseEvent object (while it is being dispatched), because it can represent the "no button currently active" state (0).

The value of the 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 value 5 indicates that the left and middle button are currently both pressed.

Some default actions related to events such as mousedown and mouseup depend on the specific mouse button in use.

The un-initialized value of this attribute MUST be 0.

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's getModifierState() 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 to 0
Initializes the screenX attribute of the MouseEvent 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 to 0
Initializes the screenY attribute of the MouseEvent 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 to 0
Initializes the clientX attribute of the MouseEvent 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 to 0
Initializes the clientY attribute of the MouseEvent 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 to 0
Initializes the button attribute of the MouseEvent 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 to 0
Initializes the buttons attribute of the MouseEvent 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 to null
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 to false
Initializes the ctrlKey attribute of the MouseEvent or KeyboardEvent objects to true if the Control 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 the getModifierState() or getModifierState() when provided with the parameter Control must return true.

shiftKey, of type boolean, defaulting to false
Initializes the shiftKey attribute of the MouseEvent or KeyboardEvent objects to true if the Shift 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 the getModifierState() or getModifierState() when provided with the parameter Shift must return true.

altKey, of type boolean, defaulting to false
Initializes the altKey attribute of the MouseEvent or KeyboardEvent objects to true if the Alt (alternative) (or Option) 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 the getModifierState() or getModifierState() when provided with the parameter Alt must return true.

metaKey, of type boolean, defaulting to false
Initializes the metaKey attribute of the MouseEvent or KeyboardEvent objects to true if the Meta 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 the getModifierState() or getModifierState() when provided with either the parameter Meta must return true.

modifierAltGraph, of type boolean, defaulting to false
Initializes the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with the parameter AltGraph must return true.
modifierCapsLock, of type boolean, defaulting to false
Initializes the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with the parameter CapsLock must return true.
modifierFn, of type boolean, defaulting to false
Initializes the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with the parameter Fn must return true.
modifierFnLock, of type boolean, defaulting to false
Initializes the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with the parameter FnLock must return true.
modifierHyper, of type boolean, defaulting to false
Initializes the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with the parameter Hyper must return true.
modifierNumLock, of type boolean, defaulting to false
Initializes the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with the parameter NumLock must return true.
modifierScrollLock, of type boolean, defaulting to false
Initializes the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with the parameter ScrollLock must return true.
modifierSuper, of type boolean, defaulting to false
Initializes the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with the parameter Super must return true.
modifierSymbol, of type boolean, defaulting to false
Initializes the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with the parameter Symbol must return true.
modifierSymbolLock, of type boolean, defaulting to false
Initializes the event object’s key modifier state such that calls to the getModifierState() or getModifierState() when provided with the parameter SymbolLock must return true.
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:

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:

For these events, the OS will be able to provide the following info:

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 Elements 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 initialize

eventType, a DOMString containing the event type

eventTarget, the EventTarget of the event

bubbles, true if this event bubbles

cancelable, true if this event is cancelable

Output

None

  1. Initialize a UIEvent with event, eventType, eventTarget, bubbles and cancelable.

  2. Initialize the following public attributes:

    1. Set event.screenX = the x-coordinate of the position where the event occurred relative to the origin of the desktop

    2. Set event.screenY = the y-coordinate of the position where the event occurred relative to the origin of the desktop

    3. Set event.clientX = the x-coordinate of the position where the event occurred relative to the origin of the viewport

    4. Set event.clientY = the y-coordinate of the position where the event occurred relative to the origin of the viewport

    5. Set mouse event modifiers with event

    6. Set event.button = 0

    7. Set event.buttons = mouse button bitmask

  3. Initialize PointerLock attributes for MouseEvent with event

3.4.3.5. set mouse event modifiers
Input

event, the MouseEvent to update

Output

None

  1. Set event’s shift flag if key modifier state includes "Shift", unset it otherwise

  2. Set event’s control flag if key modifier state includes "Control", unset it otherwise

  3. Set event’s alt flag if key modifier state includes "Alt", unset it otherwise

  4. Set event’s altgraph flag if key modifier state includes "AltGraph", unset it otherwise

  5. Set event’s meta flag if key modifier state includes "Meta", unset it otherwise

  6. Set event.shiftKey = true if the event’s shift flag is set, false otherwise

  7. Set event.ctrlKey = true if the event’s control flag is set, false otherwise

  8. Set event.altKey = true if the event’s alt flag or altgraph flag is set, false otherwise

  9. 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 type

eventTarget, the EventTarget of the event

Output

None

  1. Let bubbles be "true"

  2. Let cancelable be "true"

  3. Let event = the result of creating a new event using MouseEvent

  4. Initialize a MouseEvent with event, eventType, eventTarget, bubbles and cancelable.

  5. Return event

3.4.3.7. create a non-cancelable MouseEvent
Input

eventType, a DOMString containing a valid MouseEvent type

eventTarget, the EventTarget of the event

Output

None

  1. Let bubbles be "false"

  2. Let cancelable be "false"

  3. Let event = the result of creating a new event using MouseEvent

  4. Initialize a MouseEvent with event, eventType, eventTarget, bubbles and cancelable.

  5. 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's button attribute

  1. If mbutton is the primary mouse button, then return 0

  2. If mbutton is the auxiliary (middle) mouse button, then return 1

  3. If mbutton is the secondary mouse button, then return 2

  4. If mbutton is the X1 (back) button, then return 3

  5. If mbutton is the X2 (forward) button, then return 4

3.4.3.9. set MouseEvent attributes from native
Input

event, the MouseEvent to initialize

native, the native mouse event

Output

None

TODO

  1. If event.type is one of [ mousedown, mouseup ], then

    1. Let mbutton be an ID from native that identifies which mouse button was pressed

    2. Set event.button = calculate MouseEvent button attribute with mbutton

3.4.3.10. handle native mouse down
Input

native, the native mousedown

Output

None

  1. Let mbutton be an ID from native that identifies which mouse button was pressed

  2. Update the mouse button bitmask as follows:

    1. If mbutton is the primary mouse button, then set the 0x01 bit

    2. If mbutton is the secondary mouse button, then set the 0x02 bit

    3. If mbutton is the auxiliary (middle) mouse button, then set the 0x04 bit

    Other buttons can be added starting with 0x08

  3. Let target = hit test with viewport-relative coordinates from native

  4. Let event = create a cancelable MouseEvent with "mousedown", target

  5. Set MouseEvent attributes from native with native

  6. Maybe send pointerdown event with event

  7. Let result = dispatch event at target

  8. If result is true and target is a focusable area that is click focusable, then

    1. Run the focusing steps at target

  9. if mbutton is the secondary mouse button, then

    1. 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.

  1. Let mbutton be an ID from native that identifies which mouse button was pressed

  2. Update the mouse button bitmask as follows:

    1. If mbutton is the primary mouse button, then clear the 0x01 bit

    2. If mbutton is the secondary mouse button, then clear the 0x02 bit

    3. If mbutton is the auxiliary (middle) mouse button, then clear the 0x04 bit

  3. Let target = hit test with viewport-relative coordinates from native

  4. Let event = create a cancelable MouseEvent with "mouseup", target

  5. Set MouseEvent attributes from native with native

  6. Maybe send pointerup event with event

  7. 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.

  1. Let target = hit test with viewport-relative coordinates from native

  2. 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

  1. Let mbutton = 1 (primary mouse button by default)

  2. If native is valid, then

    1. Let mbutton be an ID from native that identifies which mouse button was pressed

  3. Set eventType = "click" if mbutton is the primary mouse button, otherwise "auxclick"

  4. Let event = create a PointerEvent with eventType and target

  5. If native is valid, then

    1. Set MouseEvent attributes from native with event, native

    2. If event.screenX is not an integer value, then round it.

    3. If event.screenY is not an integer value, then round it.

  6. 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.

  1. Let mbutton be an ID from native that identifies which mouse button was pressed

  2. If mbutton is not the primary mouse button, then return

  3. Let target = hit test with viewport-relative coordinates from native

  4. Let event = create a PointerEvent with "dblclick" and target

  5. Set MouseEvent attributes from native with event, native

  6. If event.screenX is not an integer value, then round it.

  7. If event.screenY is not an integer value, then round it.

  8. 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.

  1. Let target = hit test with viewport-relative coordinates from native

  2. Let targetDomPath = calculate DOM path

  3. Generate events for leaving the current element:

    1. If last mouse element is defined and not equal to target, then

      1. Let mouseout = create a cancelable MouseEvent with "mouseout" and last mouse element

      TODO: Set mouseout attributes from native. +CSSOM attributes

      1. Maybe send pointerout event with mouseout

      2. Dispatch mouseout at target

        Verify behavior when canceled (appears to have no effect).

      3. Let leaveElements be a copy of last mouse DOM path with all elements common to targetDomPath removed.

      4. 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.

        1. Let mouseleave = create a non-cancelable MouseEvent with "mouseleave" and element

        2. Set mouseleave.composed = false

          Check compat: Value of event.composed. Spec says false. Chrome/Linux = true. Firefox/Linux = false.

        3. Maybe send pointerleave event with mouseleave

        4. Let result = dispatch mouseleave at element

  4. Generate events for entering the new element:

    1. If target is not last mouse element, then

      1. Let mouseover = create a cancelable MouseEvent with "mouseover" and target

      TODO: Set mouseout attributes from native. +CSSOM attributes

      1. Maybe send pointerover event with mouseover

      2. Dispatch mouseout at target

        Need to verify behavior when canceled (appears to have no effect).

      3. Let enterElements be a copy of targetDomPath with all elements common to last mouse DOM path removed.

      4. For each element in enterElements, do

        Handle case where element has been deleted or moved.

        1. Let mouseenter = create a non-cancelable MouseEvent with "mouseenter" and element

        2. Set mouseenter.composed = false

          Check compat: Value of event.composed. Spec says false. Chrome/Linux = true. Firefox/Linux = false.

        3. Maybe send pointerenter event with mouseenter

        Check compat for shadow DOM elements. Chrome/Linux fires this event at the element and the shadow root.

        1. Let result = dispatch mouseenter at element

      5. Set last mouse element to target

      6. Set last mouse DOM path to targetDomPath

  5. Let mousemove = create a cancelable MouseEvent with "mousemove" and element

  6. Set PointerLock attributes for mousemove

  7. Maybe send pointermove event with mousemove

  8. 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

  1. Let menuevent = create a PointerEvent with "contextmenu", target

  2. If native is valid, then

    1. Set MouseEvent attributes from native with native

  3. Let result = dispatch menuevent at target

  4. 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:

Graphical representation of three stacked elements all on top of each other. The bottom element is labeled A and the top element is C
Graphical representation of three stacked elements all on top of each other, with the pointing device moving over the stack.

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:

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:

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 eventInitDict = {});
  // DeltaModeCode
  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 is DOM_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 to 0.0
See deltaZ attribute.
deltaY, of type double, defaulting to 0.0
See deltaZ attribute.
deltaZ, of type double, defaulting to 0.0
Initializes the deltaZ attribute of the WheelEvent object. Relative positive values for this attribute (as well as the deltaX and deltaY 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 to 0
Initializes the deltaMode attribute on the WheelEvent 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)
  • Event.target : element target for the current wheel event transaction
  • UIEvent.view : Window
  • UIEvent.detail : 0
  • MouseEvent.screenX : if the wheel is associated with a pointing device, the value based on the pointer position on the screen, otherwise 0
  • MouseEvent.screenY : if the wheel is associated with a pointing device, the value based on the pointer position on the screen, otherwise 0
  • MouseEvent.clientX : if the wheel is associated with a pointing device, the value based on the pointer position within the viewport, otherwise 0
  • MouseEvent.clientY : if the wheel is associated with a pointing device, the value based on the pointer position within the viewport, otherwise 0
  • MouseEvent.altKey : true if Alt modifier was active, otherwise false
  • MouseEvent.ctrlKey : true if Control modifier was active, otherwise false
  • MouseEvent.shiftKey : true if Shift modifier was active, otherwise false
  • MouseEvent.metaKey : true if Meta modifier was active, otherwise false
  • MouseEvent.button : if wheel is associated with a pointing device, value based on current button pressed, otherwise 0
  • MouseEvent.buttons : if wheel is associated with a pointing device, value based on all buttons current depressed, 0 if no buttons pressed
  • MouseEvent.relatedTarget : indicates the event target the pointing device is pointing at, if any
  • WheelEvent.deltaX : expected amount that the page will scroll along the x-axis according to the deltaMode units; or an implementation-specific value of movement of a wheel around the x-axis
  • WheelEvent.deltaY : expected amount that the page will scroll along the y-axis according to the deltaMode units; or an implementation-specific value of movement of a wheel around the y-axis
  • WheelEvent.deltaZ : expected amount that the page will scroll along the z-axis according to the deltaMode units; or an implementation-specific value of movement of a wheel around the z-axis
  • WheelEvent.deltaMode : unit indicator (pixels, lines, or pages) for the deltaX, deltaY, and deltaZ attributes

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 a compositionstart event and before the corresponding compositionend 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 to null
Initializes the data attribute of the InputEvent object.
isComposing, of type boolean, defaulting to false
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 eventInitDict = {});
  // KeyLocationCode
  const unsigned long DOM_KEY_LOCATION_STANDARD = 0x00;
  const unsigned long DOM_KEY_LOCATION_LEFT = 0x01;
  const unsigned long DOM_KEY_LOCATION_RIGHT = 0x02;
  const unsigned long DOM_KEY_LOCATION_NUMPAD = 0x03;

  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.
The NumLock key on a PC 101 Key US keyboard.
The 1 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).

The left Control key on a PC 101 Key US keyboard.

DOM_KEY_LOCATION_RIGHT
The key activation originated from the right key location (when there is more than one possible location for this key).

The right Shift key on a PC 101 Key US keyboard.

DOM_KEY_LOCATION_NUMPAD
The key activation originated on the numeric keypad or with a virtual key corresponding to the numeric keypad (when there is more than one possible location for this key). Note that the NumLock key should always be encoded with a location of DOM_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 legacy keyCode 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 the location attribute MUST be set to DOM_KEY_LOCATION_STANDARD. Conversely, if the "KeyQ" key is remapped to one of the Control keys, then the location attribute MUST be set to either DOM_KEY_LOCATION_LEFT or DOM_KEY_LOCATION_RIGHT.

The un-initialized value of this attribute MUST be 0.

ctrlKey, of type boolean, readonly
true if the Control (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 the Alt (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 events keydown, 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 a repeat attribute value of true MUST serve as an indication of a long-key-press. The length of time that the key MUST be pressed in order to begin repeating is configuration-dependent.

The un-initialized value of this attribute MUST be false.

isComposing, of type boolean, readonly
true if the key event occurs as part of a composition session, i.e., after a compositionstart event and before the corresponding compositionend 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 to 0
Initializes the location attribute of the KeyboardEvent object to one of the following location numerical constants:
repeat, of type boolean, defaulting to false
Initializes the repeat attribute of the KeyboardEvent object. This attribute should be set to true 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 to false
Initializes the isComposing attribute of the KeyboardEvent object. This attribute should be set to true if the event being constructed occurs as part of a composition sequence, false otherwise.
Legacy keyboard event implementations include three additional attributes, keyCode, charCode, and which. The keyCode attribute indicates a numeric value associated with a particular key on a computer keyboard, while the charCode attribute indicates the ASCII value of the character associated with that key (which might be the same as the keyCode value) and is applicable only to keys that produce a character value.

In practice, keyCode and charCode are inconsistent across platforms and even the same implementation on different operating systems or using different localizations. 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 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 CompositionEvent interface, use the CompositionEvent constructor, passing an optional CompositionEventInit dictionary.

3.8.1.1. CompositionEvent
[Exposed=Window]
interface CompositionEvent : UIEvent {
  constructor(DOMString type, optional CompositionEventInit eventInitDict = {});
  readonly attribute USVString data;
};
data, of type USVString, readonly
data holds the value of the characters generated by an input method. This MAY be a single Unicode character or a non-empty sequence of Unicode characters [Unicode]. Characters SHOULD be normalized as defined by the Unicode normalization form NFC, defined in [UAX15]. This attribute MAY be the empty string.

The un-initialized value of this attribute MUST be "" (the empty string).

3.8.1.2. CompositionEventInit
dictionary CompositionEventInit : UIEventInit {
  DOMString data = "";
};
data, of type DOMString, defaulting to ""
Initializes the data attribute of the CompositionEvent object to the characters generated by the IME composition.

3.8.2. Composition Event Order

The Composition Events defined in this specification MUST occur in the following set order relative to one another:

Event Type Notes
1 compositionstart
2 compositionupdate Multiple events
3 compositionend

3.8.3. Handwriting Recognition Systems

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

Event Type CompositionEvent
data
Notes
1 compositionstart ""
User writes word on tablet surface
2 compositionupdate "test"
User rejects first word-match suggestion, selects different match
3 compositionupdate "text"
4 compositionend "text"

3.8.4. Canceling Composition Events

If a keydown event is canceled then any Composition Events that would have fired as a result of that keydown SHOULD not be dispatched:

Event Type Notes
1 keydown The default action is prevented, e.g., by invoking preventDefault().
No Composition Events are dispatched
2 keyup

If the initial compositionstart event is canceled then the text composition session SHOULD be terminated. Regardless of whether or not the composition session is terminated, the compositionend event MUST be sent.

Event Type Notes
1 keydown
2 compositionstart The default action is prevented, e.g., by invoking preventDefault().
No Composition Events are dispatched
3 compositionend
4 keyup

3.8.5. Key Events During Composition

During the composition session, keydown and keyup events MUST still be sent, and these events MUST have the isComposing attribute set to true.

Event Type KeyboardEvent
isComposing
Notes
1 keydown false This is the key event that initiates the composition.
2 compositionstart
3 compositionupdate
4 keyup true
... Any key events sent during the composition session MUST have isComposing set to true.
5 keydown true This is the key event that exits the composition.
6 compositionend
7 keyup false

3.8.6. Input Events During Composition

During the composition session, the compositionupdate MUST be dispatched after the beforeinput is sent, but before the input event is sent.

Event Type Notes
1 beforeinput
2 compositionupdate
Any DOM updates occur at this point.
3 input

Most IMEs do not support canceling updates during a composition session.

The beforeinput and input events are sent along with the compositionupdate event whenever the DOM is updated as part of the composition. Since there are no DOM updates associated with the compositionend event, beforeinput and input events should not be sent at that time.

Event Type Notes
1 beforeinput Canceling this will prevent the DOM update and the input event.
2 compositionupdate
Any DOM updates occur at this point.
3 input Sent only if the DOM was updated.
4 compositionend

3.8.7. Composition Event Types

3.8.7.1. compositionstart
Type compositionstart
Interface CompositionEvent
Sync / Async Sync
Bubbles Yes
Trusted Targets Element
Cancelable Yes
Composed Yes
Default action Start a new composition session when a text composition system is enabled
Context
(trusted events)

A user agent MUST dispatch this event when a text composition system is enabled and a new composition session is about to begin (or has begun, depending on the text composition system) in preparation for composing a passage of text. This event type is device-dependent, and MAY rely upon the capabilities of the text conversion system and how it is mapped into the operating system. When a keyboard is used to feed an input method editor, this event type is generated after a keydown event, but speech or handwriting recognition systems MAY send this event type without keyboard events. Some implementations MAY populate the data attribute of the compositionstart event with the text currently selected in the document (for editing and replacement). Otherwise, the value of the data attribute MUST be the empty string.

This event MUST be dispatched immediately before a text composition system begins a new composition session, and before the DOM is modified due to the composition process. The default action of this event is for the text composition system to start a new composition session. If this event is canceled, the text composition system SHOULD discard the current composition session.

Canceling the compositionstart event type is distinct from canceling the text composition system itself (e.g., by hitting a cancel button or closing an IME window).

Some IMEs do not support cancelling an in-progress composition session (e.g., such as GTK which doesn’t presently have such an API). In these cases, calling preventDefault() will not stop this event’s default action.

3.8.7.2. compositionupdate
Type compositionupdate
Interface CompositionEvent
Sync / Async Sync
Bubbles Yes
Trusted Targets Element
Cancelable No
Composed Yes
Default action None
Context
(trusted events)

A user agent SHOULD dispatch this event during a composition session when a text composition system updates its active text passage with a new character, which is reflected in the string in data.

In text composition systems which keep the ongoing composition in sync with the input control, the compositionupdate event MUST be dispatched before the control is updated.

Some text composition systems might not expose this information to the DOM, in which case this event will not fire during the composition process.

If the composition session is canceled, this event will be fired immediately before the compositionend event, and the data attribute will be set to the empty string.

3.8.7.3. compositionend
Type compositionend
Interface CompositionEvent
Sync / Async Sync
Bubbles Yes
Trusted Targets Element
Cancelable No
Composed Yes
Default action None
Context
(trusted events)

A user agent MUST dispatch this event when a text composition system completes or cancels the current composition session, and the compositionend event MUST be dispatched after the control is updated.

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

4. Keyboard events and key values

This section contains necessary information regarding keyboard events:

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

4.1. Keyboard Input

This section is non-normative

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

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

4.1.1. Key Legends

This section is informative

The key legend is the visual marking that is printed or embossed on the key cap (the rectangular "cap" that covers the mechanical switch for the key). These markings normally consist of one or more characters that a keystroke on that key will produce (such as "G", "8", or "ш"), or names or symbols which indicate that key’s function (such as an upward-pointing arrow "⇧" indicating Shift, or the string "Enter"). Keys are often referred to by this marking (e.g., Press the "Shift" and "G" keys.). Note, however, that the visual appearance of the key has no bearing on its digital representation, and in many configurations may be completely inaccurate. Even the control and function keys, such as Enter, may be mapped to different functionality, or even mapped as character keys.

Many keyboards contain keys that do not normally produce any characters, even though the symbol might have a Unicode equivalent. For example, the Shift key might bear the symbol "⇧", which has the Unicode code point U+21E7, but pressing the Shift key will not produce this character value, and there is no Unicode code point for Shift.

4.2. Key codes

A key code is an attribute of a keyboard event that can be used to identify the physical key associated with the keyboard event. It is similar to USB Usage IDs in that it provides a low-level value (similar to a scancode) that is vendor-neutral.

The primary purpose of the code attribute is to provide a consistent and coherent way to identify keys based on their physical location. In addition, it also provides a stable name (unaffected by the current keyboard state) that uniquely identifies each key on the keyboard.

The list of valid code values is defined in the [UIEvents-Code].

4.2.1. Motivation for the code Attribute

The standard PC keyboard has a set of keys (which we refer to as writing system keys) that generate different key values based on the current keyboard layout selected by the user. This situation makes it difficult to write code that detects keys based on their physical location since the code would need to know which layout is in effect in order to know which key values to check for. A real-world example of this is a game that wants to use the "W", "A", "S" and "D" keys to control player movement. The code attribute solves this problem by providing a stable value to check that is not affected by the current keyboard layout.

In addition, the values in the key attribute depend as well on the current keyboard state. Because of this, the order in which keys are pressed and released in relation to modifier keys can affect the values stored in the key attribute. The code attribute solves this problem by providing a stable value that is not affected by the current keyboard state.

4.2.2. The Relationship Between key and code

key
The key attribute is intended for users who are interested in the meaning of the key being pressed, taking into account the current keyboard layout (and IME; dead keys are given a unique key value). Example use case: Detecting modified keys or bare modifier keys (e.g., to perform an action in response to a keyboard shortcut).
code
The code attribute is intended for users who are interested in the key that was pressed by the user, without any layout modifications applied. Example use case: Detecting WASD keys (e.g., for movement controls in a game) or trapping all keys (e.g., in a remote desktop client to send all keys to the remote host).

4.2.3. code Examples

Handling the Left and Right Alt Keys
Keyboard Layout KeyboardEvent
key
KeyboardEvent
code
Notes
US "Alt" "AltLeft" DOM_KEY_LOCATION_LEFT
French "Alt" "AltLeft" DOM_KEY_LOCATION_LEFT
US "Alt" "AltRight" DOM_KEY_LOCATION_RIGHT
French "AltGraph" "AltRight" DOM_KEY_LOCATION_RIGHT

In this example, checking the key attribute permits matching Alt without worrying about which Alt key (left or right) was pressed. Checking the code attribute permits matching the right Alt key ("AltRight") without worrying about which layout is currently in effect.

Note that, in the French example, the Alt and AltGraph keys retain their left and right location, even though there is only one of each key.

Handling the Single Quote Key
Keyboard Layout KeyboardEvent
key
KeyboardEvent
code
Notes
US "'" "Quote"
Japanese ":" "Quote"
US Intl "Dead" "Quote"

This example shows how dead key values are encoded in the attributes. The key values vary based on the current locale, whereas the code attribute returns a consistent value.

Handling the "2" Key (with and without Shift pressed) on various keyboard layouts.
Keyboard Layout KeyboardEvent
key
KeyboardEvent
code
Notes
US "2" "Digit2"
US "@" "Digit2" shiftKey
UK "2" "Digit2"
UK """ "Digit2" shiftKey
French "é" "Digit2"
French "2" "Digit2" shiftKey

Regardless of the current locale or the modifier key state, pressing the key labelled "2" on a US keyboard always results in "Digit2" in the code attribute.

Sequence of Keyboard Events : Shift and 2

Compare the attribute values in the following two key event sequences. They both produce the "@" character on a US keyboard, but differ in the order in which the keys are released. In the first sequence, the order is: Shift (down), 2 (down), 2 (up), Shift (up).

Event Type KeyboardEvent
key
KeyboardEvent
code
Notes
1 keydown "Shift" "ShiftLeft" DOM_KEY_LOCATION_LEFT
2 keydown "@" "Digit2" shiftKey
3 keypress "@" "Digit2" (if supported)
4 keyup "@" "Digit2" shiftKey
5 keyup "Shift" "ShiftLeft" DOM_KEY_LOCATION_LEFT

In the second sequence, the Shift is released before the 2, resulting in the following event order: Shift (down), 2 (down), Shift (up), 2 (up).

Event Type KeyboardEvent
key
KeyboardEvent
code
Notes
1 keydown "Shift" "ShiftLeft" DOM_KEY_LOCATION_LEFT
2 keydown "@" "Digit2" shiftKey
3 keypress "@" "Digit2" (if supported)
4 keyup "Shift" "ShiftLeft" DOM_KEY_LOCATION_LEFT
5 keyup "2" "Digit2"

Note that the values contained in the key attribute does not match between the keydown and keyup events for the "2" key. The code attribute provides a consistent value that is not affected by the current modifier state.

4.2.4. code and Virtual Keyboards

The usefulness of the code attribute is less obvious for virtual keyboards (and also for remote controls and chording keyboards). In general, if a virtual (or remote control) keyboard is mimicking the layout and functionality of a standard keyboard, then it MUST also set the code attribute as appropriate. For keyboards which are not mimicking the layout of a standard keyboard, then the code attribute MAY be set to the closest match on a standard keyboard or it MAY be left undefined.

For virtual keyboards with keys that produce different values based on some modifier state, the code value should be the key value generated when the button is pressed while the device is in its factory-reset state.

4.3. Keyboard Event key Values

A key value is a DOMString that can be used to indicate any given key on a keyboard, regardless of position or state, by the value it produces. These key values MAY be used as return values for keyboard events generated by the implementation, or as input values by the content author to specify desired input (such as for keyboard shortcuts).

The list of valid key values is defined in [UIEvents-Key].

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

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

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

A key value does not indicate a specific key on the physical keyboard, nor does it reflect the character printed on the key. A key value indicates the current value of the event with consideration to the current state of all active keys and key input modes (including shift modes), as reflected in the operating-system mapping of the keyboard and reported to the implementation. In other words, the key value for the key labeled O on a QWERTY keyboard has the key value "o" in an unshifted state and "O" in a shifted state. Because a user can map their keyboard to an arbitrary custom configuration, the content author is encouraged not to assume that a relationship exists between the shifted and unshifted states of a key and the majuscule form (uppercase or capital letters) and minuscule form (lowercase or small letters) of a character representation, but is encouraged instead to use the value of the key attribute. For example, the Standard "102" Keyboard layout depicted in [UIEvents-Code] illustrates one possible set of key mappings on one possible keyboard layout. Many others exist, both standard and idiosyncratic.

To simplify dead key support, when the operating-system mapping of the keyboard is handling a dead key state, the current state of the dead key sequence is not reported via the key attribute. Rather, a key value of "Dead" is reported. Instead, implementations generate composition events which contain the intermediate state of the dead key sequence reported via the data attribute. As in the previous example, the key value for the key marked O on a QWERTY keyboard has a data value of "ö" in an unshifted state during a dead-key operation to add an umlaut diacritic, and "Ö" in a shifted state during a dead-key operation to add an umlaut diacritic.

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

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

4.3.1. Modifier keys

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

This example describes a possible sequence of events associated with the generation of the Unicode character Q (Latin Capital Letter Q, Unicode code point U+0051) on a US keyboard using a US mapping:
Event Type KeyboardEvent
key
Modifiers Notes
1 keydown "Shift" shiftKey
2 keydown "Q" shiftKey Latin Capital Letter Q
3 beforeinput
4 input
5 keyup "Q" shiftKey
6 keyup "Shift"
Th example describes an alternate sequence of keys to the example above, where the Shift key is released before the Q key. The key value for the Q key will revert to its unshifted value for the keyup event:
Event Type KeyboardEvent
key
Modifiers Notes
1 keydown "Shift" shiftKey
2 keydown "Q" shiftKey Latin Capital Letter Q
3 beforeinput
4 input
5 keyup "Shift"
6 keyup "q" Latin Small Letter Q
The following example describes a possible sequence of keys that does not generate a Unicode character (using the same configuration as the previous example):
Event Type KeyboardEvent
key
Modifiers Notes
1 keydown "Control" ctrlKey
2 keydown "v" ctrlKey Latin Small Letter V
No beforeinput or input events are generated.
3 keyup "v" ctrlKey Latin Small Letter V
4 keyup "Control"
The following example shows the sequence of events when both Shift and Control are pressed:
Event Type KeyboardEvent
key
Modifiers Notes
1 keydown "Control" ctrlKey
2 keydown "Shift" ctrlKey, shiftKey
3 keydown "V" ctrlKey, shiftKey Latin Capital Letter V
No beforeinput or input events are generated.
4 keyup "V" ctrlKey, shiftKey Latin Capital Letter V
5 keyup "Shift" ctrlKey
6 keyup "Control"
For non-US keyboard layouts, the sequence of events is the same, but the value of the key is based on the current keyboard layout. This example shows a sequence of events when an Arabic keyboard layout is used:
Event Type KeyboardEvent
key
Modifiers Notes
1 keydown "Control" ctrlKey
2 keydown "ر" ctrlKey Arabic Letter Reh
No beforeinput or input events are generated.
3 keyup "ر" ctrlKey Arabic Letter Reh
4 keyup "Control"

The value in the keydown and keyup events varies based on the current keyboard layout in effect when the key is pressed. This means that the v key on a US layout and the ر key on an Arabic layout will generate different events even though they are the same physical key. To identify these events as coming from the same physical key, you will need to make use of the code attribute.

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

4.3.2. Dead keys

Some keyboard input uses dead keys for the input of composed character sequences. Unlike the handwriting sequence, in which users enter the base character first, keyboard input requires to enter a special state when a dead key is pressed and emit the character(s) only when one of a limited number of legal base character is entered.

The MacOS and Linux operating systems use input methods to process dead keys.

The dead keys (across all keyboard layouts and mappings) are represented by the key value Dead. In response to any dead key press, composition events must be dispatched by the user agent and the compositionupdate event’s data value must be the character value of the current state of the dead key combining sequence.

While Unicode combining characters always follow the handwriting sequence, with the combining character trailing the corresponding letter, typical dead key input MAY reverse the sequence, with the combining character before the corresponding letter. For example, the word naïve, using the combining diacritic ¨, would be represented sequentially in Unicode as nai¨ve, but MAY be typed na¨ive. The sequence of keystrokes U+0302 (Combining Circumflex Accent key) and U+0065 (key marked with the Latin Small Letter E) will likely produce (on a French keyboard using a french mapping and without any modifier activated) the Unicode character "ê" (Latin Small Letter E With Circumflex), as preferred by the Unicode Normalization Form NFC.

Event Type KeyboardEvent
key
KeyboardEvent
isComposing
CompositionEvent
data
Notes
1 keydown "Dead" false Combining Circumflex Accent (Dead Key)
2 compositionstart ""
3 compositionupdate U+0302
4 keyup "Dead" true
5 keydown "ê" true
6 compositionupdate "ê"
7 compositionend "ê"
8 keyup "e" false Latin Small Letter E

In the second keydown event (step 5), the key value (assuming the event is not suppressed) will not be "e" (Latin Small Letter E key) under normal circumstances because the value delivered to the user agent will already be modified by the dead key operation.

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

Event Type KeyboardEvent
key
KeyboardEvent
isComposing
CompositionEvent
data
Notes
1 keydown "Dead" false Combining Circumflex Accent (Dead Key)
2 compositionstart ""
3 compositionupdate U+0302
4 keyup "Dead" true
5 keydown "q" true Latin Small Letter Q
6 compositionupdate ""
7 compositionend ""
8 keyup "q" false

4.3.3. Input Method Editors

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

In some implementations or system configurations, some key events, or their values, might be suppressed by the IME in use.

The following example describes a possible sequence of keys to generate the Unicode character "市" (Kanji character, part of CJK Unified Ideographs) using Japanese input methods. This example assumes that the input method editor is activated and in the Japanese-Romaji input mode. The keys Convert and Accept MAY be replaced by others depending on the input device in use and the configuration of the IME, e.g., it can be respectively U+0020 (Space key) and Enter.

"詩" (poem) and "市" (city) are homophones, both pronounced し (shi/si), so the user needs to use the Convert key to select the proper option.

Event Type KeyboardEvent
key
KeyboardEvent
isComposing
CompositionEvent
data
Notes
1 keydown "s" false Latin Small Letter S
2 compositionstart ""
3 beforeinput
4 compositionupdate "s"
DOM is updated
5 input
6 keyup "s" true
7 keydown "i" true Latin Small Letter I
8 beforeinput
9 compositionupdate "し" shi
DOM is updated
10 input
11 keyup "i" true
12 keydown "Convert" true Convert
13 beforeinput
14 compositionupdate "詩" "poem"
DOM is updated
15 input
16 keyup "Convert" true
17 keydown "Convert" true Convert
18 beforeinput
19 compositionupdate "市" "city"
DOM is updated
20 input
21 keyup "Convert" true
22 keydown "Accept" true Accept
23 compositionend "市"
24 keyup "Accept" false

IME composition can also be canceled as in the following example, with conditions identical to the previous example. The key Cancel might also be replaced by others depending on the input device in use and the configuration of the IME, e.g., it could be U+001B (Escape key).

Event Type KeyboardEvent
key
KeyboardEvent
isComposing
CompositionEvent
data
Notes
1 keydown "s" false Latin Small Letter S
2 compositionstart ""
3 compositionupdate "s"
4 keyup "s" true
5 keydown "i" true Latin Small Letter I
6 compositionupdate "し" shi
7 keyup "i" true
8 keydown "Convert" true Convert
9 compositionupdate "詩" "poem"
10 keyup "Convert" true
11 keydown "Convert" true Convert
12 compositionupdate "市" "city"
13 keyup "Convert" true
14 keydown "Cancel" true Cancel
15 compositionupdate ""
16 compositionend ""
17 keyup "Cancel" false

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

4.3.3.1. Input Method Editor mode keys

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

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

Keys with input method editor functions are not restricted to that purpose, and can have other device- or implementation-specific purposes.

4.3.4. Default actions and cancelable keyboard events

Canceling the default action of a keydown event MUST NOT affect its respective keyup event, but it MUST prevent the respective beforeinput and input (and keypress if supported) events from being generated. The following example describes a possible sequence of keys to generate the Unicode character Q (Latin Capital Letter Q) on a US keyboard using a US mapping:

Event Type KeyboardEvent
key
InputEvent
data
Modifiers Notes
1 keydown "Shift" shiftKey
2 keydown "Q" shiftKey The default action is prevented, e.g., by invoking preventDefault().
No beforeinput or input (or keypress, if supported) events are generated
3 keyup "Q" shiftKey
4 keyup "Shift"

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

Event Type KeyboardEvent
key
InputEvent
data
Modifiers Notes
1 keydown "Shift" shiftKey The default action is prevented, e.g., by invoking preventDefault().
2 keydown "Q" shiftKey
3 beforeinput "Q"
4 input
5 keyup "Q" shiftKey
6 keyup "Shift"

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

Event Type KeyboardEvent
key
InputEvent
data
Notes
1 keydown "Dead" The default action is prevented, e.g., by invoking preventDefault().
2 keyup "Dead"
3 keydown "e"
4 beforeinput "e"
5 input
6 keyup "e"

5. External Algorithms

This sections contains algorithms that are required by this specification, but are more properly hosted by other specifications.

The intent is that this sections serve as a temporary home for these definitions, and they should eventually be moved into a more appropriate home so this entire section can be deleted.

5.1. Core DOM Algorithms

The following algorithms should be moved... somewhere.

5.1.1. hit test

Input

pos, the x,y coordinates relative to the viewport

Output

The frontmost DOM element at pos

To account for inert or disabled elements. this should call elementsFromPoint and reject invalid elements

  1. Return [CSSOM-View]'s elementFromPoint with pos

5.1.2. calculate DOM path

Input

element, the starting element

Output

The list of ancestor elements for the given element

  1. Let path = A list that contains element

    This needs a proper definition to add ancestors to path.

  2. Return path

5.2. PointerLock Algorithms

The following algorithm should be moved into the [PointerLock] spec.

5.2.1. Global State for PointerLock

5.2.1.1. Window-Level State

The UA must maintain the following values that are shared for the Window.

A last mouse move value (initially undefined) that records the position of the last mousemove event.

5.2.2. initialize PointerLock attributes for MouseEvent

Input

event, a MouseEvent

Output

None

  1. Set event.movementX = 0

  2. Set event.movementY = 0

5.2.3. set PointerLock attributes for mousemove

Input

event, a MouseEvent

Output

None

  1. If event.type is not "mousemove", then exit

  2. If last mouse move is not defined, then

    1. Set event.movementX = 0

    2. Set event.movementY = 0

  3. Otherwise,

    1. Set event.movementX = event.screenX - last mouse move’s x-coordinate

    2. Set event.movementY = event.screenX - last mouse move’s y-coordinate

  4. Set last mouse move = ( event.screenX, event.screenY )

5.3. PointerEvent Algorithms

The following algorithms should be moved into the [PointerEvents3] spec.

5.3.1. initialize a PointerEvent

Input

event, the PointerEvent to initialize

eventType, a DOMString containing the event type

eventTarget, the EventTarget of the event

Output

None

  1. Initialize a MouseEvent with event, eventType and eventTarget

TODO - initialize the pointerevent attributes

5.3.2. create a PointerEvent

Input

eventType, a DOMString containing the event type

eventTarget, the EventTarget of the event

Output

None

  1. Let event = the result of creating a new event using PointerEvent

  2. Initialize a PointerEvent with event, eventType and eventTarget

  3. Return event

5.3.3. create PointerEvent from MouseEvent

Input

eventType, a DOMString containing the event type

mouseevent, the corresponding MouseEvent

Output

None

  1. Let event = the result of creating a new event using PointerEvent

  2. Let target = mouseevent.target

  3. Initialize a PointerEvent with event, eventType and target

  4. Copy MouseEvent attributes from mouseevent into event

  5. Return event

5.3.4. maybe send pointerout event

Input

mouseout, the corresponding mouseout MouseEvent

Output

None

  1. Let pointerout = create PointerEvent from MouseEvent with "pointerout" and mouseout

  2. Set pointerevent attributes

    TODO

  3. Let target = mouseout.target

  4. dispatch pointerout at target

5.3.5. maybe send pointerleave event

Input

mouseout, the corresponding mouseout MouseEvent

Output

None

  1. Let pointerout = create PointerEvent from MouseEvent with "pointerout" and mouseout

  2. Set pointerevent attributes

    TODO

  3. Let target = mouseout.target

  4. dispatch pointerout at target

5.3.6. maybe send pointerover event

Input

mouseout, the corresponding mouseout MouseEvent

Output

None

  1. Let pointerout = create PointerEvent from MouseEvent with "pointerout" and mouseout

  2. Set pointerevent attributes

    TODO

  3. Let target = mouseout.target

  4. dispatch pointerout at target

5.3.7. maybe send pointerenter event

Input

mouseout, the corresponding mouseout MouseEvent

Output

None

  1. Let pointerout = create PointerEvent from MouseEvent with "pointerout" and mouseout

  2. Set pointerevent attributes

    TODO

  3. Let target = mouseout.target

  4. dispatch pointerout at target

5.3.8. maybe send pointermove event

Input

mouseout, the corresponding mouseout MouseEvent

Output

None

Can this send pointermove and pointerrawupdate? Or do we need 2 methods?

What is needed to properly define how pointermove events are coalesced?

  1. Let pointerout = create PointerEvent from MouseEvent with "pointerout" and mouseout

  2. Set pointerevent attributes

    TODO

  3. Let target = mouseout.target

  4. dispatch pointerout at target

5.3.9. maybe send pointerdown event

Input

mouseout, the corresponding mouseout MouseEvent

Output

None

Unlike mousedown events, pointerdown events are not nested when multiple buttons are pressed. The MouseEvent is passed so that the fields can be copied into the PointerEvent.

  1. Let pointerout = create PointerEvent from MouseEvent with "pointerout" and mouseout

  2. Set pointerevent attributes

    TODO

  3. Let target = mouseout.target

  4. dispatch pointerout at target

5.3.10. maybe send pointerup event

Input

mouseout, the corresponding mouseout MouseEvent

Output

None

Unlike mouseup events, pointerup events are not nested when multiple buttons are pressed. The MouseEvent is passed so that the fields can be copied into the PointerEvent.

  1. Let pointerout = create PointerEvent from MouseEvent with "pointerout" and mouseout

  2. Set pointerevent attributes

    TODO

  3. Let target = mouseout.target

  4. dispatch pointerout at target

6. Legacy Event Initializers

This section is normative. The following features are obsolete and should only be implemented by user agents that require compatibility with legacy software.

Early versions of this specification included an initialization method on the interface (for example initMouseEvent) that required a long list of parameters that, in most cases, did not fully initialize all attributes of the event object. Because of this, event interfaces which were derived from the basic Event interface required that the initializer of each of the derived interfaces be called explicitly in order to fully initialize an event.

Initializing all the attributes of a UIEvent requires calls to two initializer methods: initEvent and initUIEvent.

Due in part to the length of time in the development of this standard, some implementations MAY have taken a dependency on these (now deprecated) initializer methods. For completeness, these legacy event initializers are described in this Appendix.

6.1. Legacy Event Initializer Interfaces

This section is informative

This section documents legacy initializer methods that were introduced in earlier versions of this specification.

6.1.1. Initializers for interface UIEvent

partial interface UIEvent {
  // Deprecated in this specification
  undefined initUIEvent(DOMString typeArg,
    optional boolean bubblesArg = false,
    optional boolean cancelableArg = false,
    optional Window? viewArg = null,
    optional long detailArg = 0);
};
initUIEvent(typeArg)
Initializes attributes of an UIEvent object. This method has the same behavior as initEvent().

The initUIEvent method is deprecated, but supported for backwards-compatibility with widely-deployed implementations.

DOMString typeArg
Refer to the initEvent() method for a description of this parameter.
boolean bubblesArg
Refer to the initEvent() method for a description of this parameter.
boolean cancelableArg
Refer to the initEvent() method for a description of this parameter.
Window? viewArg
Specifies view. This value MAY be null.
long detailArg
Specifies detail.

6.1.2. Initializers for interface MouseEvent

partial interface MouseEvent {
  // Deprecated in this specification
  undefined initMouseEvent(DOMString typeArg,
    optional boolean bubblesArg = false,
    optional boolean cancelableArg = false,
    optional Window? viewArg = null,
    optional long detailArg = 0,
    optional long screenXArg = 0,
    optional long screenYArg = 0,
    optional long clientXArg = 0,
    optional long clientYArg = 0,
    optional boolean ctrlKeyArg = false,
    optional boolean altKeyArg = false,
    optional boolean shiftKeyArg = false,
    optional boolean metaKeyArg = false,
    optional short buttonArg = 0,
    optional EventTarget? relatedTargetArg = null);
};
initMouseEvent(typeArg)
Initializes attributes of a MouseEvent object. This method has the same behavior as UIEvent.initUIEvent().

The initMouseEvent method is deprecated, but supported for backwards-compatibility with widely-deployed implementations.

DOMString typeArg
Refer to the initEvent() method for a description of this parameter.
boolean bubblesArg
Refer to the initEvent() method for a description of this parameter.
boolean cancelableArg
Refer to the initEvent() method for a description of this parameter.
Window? viewArg
Specifies view. This value MAY be null.
long detailArg
Specifies detail.
long screenXArg
Specifies screenX.
long screenYArg
Specifies screenY.
long clientXArg
Specifies clientX.
long clientYArg
Specifies clientY.
boolean ctrlKeyArg
Specifies ctrlKey.
boolean altKeyArg
Specifies altKey.
boolean shiftKeyArg
Specifies shiftKey.
boolean metaKeyArg
Specifies metaKey.
short buttonArg
Specifies button.
EventTarget? relatedTargetArg
Specifies relatedTarget. This value MAY be null.

6.1.3. Initializers for interface KeyboardEvent

The argument list to this legacy KeyboardEvent initializer does not include the detailArg (present in other initializers) and adds the locale argument; it is necessary to preserve this inconsistency for compatibility with existing implementations.

partial interface KeyboardEvent {
  // Originally introduced (and deprecated) in this specification
  undefined initKeyboardEvent(DOMString typeArg,
    optional boolean bubblesArg = false,
    optional boolean cancelableArg = false,
    optional Window? viewArg = null,
    optional DOMString keyArg = "",
    optional unsigned long locationArg = 0,
    optional boolean ctrlKey = false,
    optional boolean altKey = false,
    optional boolean shiftKey = false,
    optional boolean metaKey = false);
};
initKeyboardEvent(typeArg)
Initializes attributes of a KeyboardEvent object. This method has the same behavior as UIEvent.initUIEvent(). The value of detail remains undefined.

The initKeyboardEvent method is deprecated.

DOMString typeArg
Refer to the initEvent() method for a description of this parameter.
boolean bubblesArg
Refer to the initEvent() method for a description of this parameter.
boolean cancelableArg
Refer to the initEvent() method for a description of this parameter.
Window? viewArg
Specifies view. This value MAY be null.
DOMString keyArg
Specifies key.
unsigned long locationArg
Specifies location.
boolean ctrlKey
Specifies whether the Control key modifier is active.
boolean altKey
Specifies whether the Alt key modifier is active.
boolean shiftKey
Specifies whether the Shift key modifier is active.
boolean metaKey
Specifies whether the Meta key modifier is active.

6.1.4. Initializers for interface CompositionEvent

The argument list to this legacy CompositionEvent initializer does not include the detailArg (present in other initializers) and adds the locale argument; it is necessary to preserve this inconsistency for compatibility with existing implementations.

partial interface CompositionEvent {
  // Originally introduced (and deprecated) in this specification
  undefined initCompositionEvent(DOMString typeArg,
    optional boolean bubblesArg = false,
    optional boolean cancelableArg = false,
    optional WindowProxy? viewArg = null,
    optional DOMString dataArg = "");
};
initCompositionEvent(typeArg)
Initializes attributes of a CompositionEvent object. This method has the same behavior as UIEvent.initUIEvent(). The value of detail remains undefined.

The initCompositionEvent method is deprecated.

DOMString typeArg
Refer to the initEvent() method for a description of this parameter.
boolean bubblesArg
Refer to the initEvent() method for a description of this parameter.
boolean cancelableArg
Refer to the initEvent() method for a description of this parameter.
Window? viewArg
Specifies view. This value MAY be null.
DOMString dataArg
Specifies data.

7. Legacy Key & Mouse Event Attributes

This section is non-normative. The following attributes are obsolete and should only be implemented by user agents that require compatibility with legacy software that requires these keyboard events.

These features were never formally specified and the current browser implementations vary in significant ways. The large amount of legacy content, including script libraries, that relies upon detecting the user agent and acting accordingly means that any attempt to formalize these legacy attributes and events would risk breaking as much content as it would fix or enable. Additionally, these attributes are not suitable for international usage, nor do they address accessibility concerns.

Therefore, this specification does not normatively define the events and attributes commonly employed for handling keyboard input, though they MAY be present in user agents for compatibility with legacy content. Authors SHOULD use the key attribute instead of the charCode and keyCode attributes.

However, for the purpose of documenting the current state of these features and their relation to normative events and attributes, this section provides an informative description. For implementations which do support these attributes and events, it is suggested that the definitions provided in this section be used.

7.1. Legacy UIEvent supplemental interface

This section is non-normative

User agents have traditionally included a which attribute so that KeyboardEvents and MouseEvents could record supplemental event info.

Previous versions of this specification defined separate which attributes directly on KeyboardEvent and MouseEvent rather than having a shared which attribute defined on UIEvent.

7.1.1. Interface UIEvent (supplemental)

The partial UIEvent interface is an informative extension of the UIEvent interface, which adds the which attribute.

partial interface UIEvent {
  // The following support legacy user agents
  readonly attribute unsigned long which;
};
which, of type unsigned long, readonly
For MouseEvents, this contains a value equal to the value stored in button+1. For KeyboardEvents, this holds a system- and implementation-dependent numerical code signifying the unmodified identifier associated with the key pressed. In most cases, the value is identical to keyCode.

7.1.2. Interface UIEventInit (supplemental)

Browsers that include support for which in UIEvent should also add the following members to the UIEventInit dictionary.

The partial UIEventInit dictionary is an informative extension of the UIEventInit dictionary, which adds the which member to initialize the corresponding UIEvent attributes.

partial dictionary UIEventInit {
  unsigned long which = 0;
};
which, of type unsigned long, defaulting to 0
Initializes the which attribute of the UIEvent.

7.2. Legacy KeyboardEvent supplemental interface

This section is non-normative

Browser support for keyboards has traditionally relied on three ad-hoc attributes, keyCode, charCode, and UIEvent's which.

All three of these attributes return a numerical code that represents some aspect of the key pressed: keyCode is an index of the key itself. charCode is the ASCII value of the character keys. which is the character value where available and otherwise the key index. The values for these attributes, and the availability of the attribute, is inconsistent across platforms, keyboard languages and layouts, user agents, versions, and even event types.

7.2.1. Interface KeyboardEvent (supplemental)

The partial KeyboardEvent interface is an informative extension of the KeyboardEvent interface, which adds the charCode and keyCode attributes.

The partial KeyboardEvent interface can be obtained by using the createEvent() method call in implementations that support this extension.

partial interface KeyboardEvent {
  // The following support legacy user agents
  readonly attribute unsigned long charCode;
  readonly attribute unsigned long keyCode;
};
charCode, of type unsigned long, readonly
charCode holds a character value, for keypress events which generate character input. The value is the Unicode reference number (code point) of that character (e.g. event.charCode = event.key.charCodeAt(0) for printable characters). For keydown or keyup events, the value of charCode is 0.
keyCode, of type unsigned long, readonly
keyCode holds a system- and implementation-dependent numerical code signifying the unmodified identifier associated with the key pressed. Unlike the key attribute, the set of possible values are not normatively defined in this specification. Typically, these value of the keyCode SHOULD represent the decimal codepoint in ASCII [RFC20][US-ASCII] or Windows 1252 [WIN1252], but MAY be drawn from a different appropriate character set. Implementations that are unable to identify a key use the key value 0.

See § 7.3 Legacy key models for more details on how to determine the values for keyCode.

7.2.2. Interface KeyboardEventInit (supplemental)

Browsers that include support for keyCode and charCode in KeyboardEvent should also add the following members to the KeyboardEventInit dictionary.

The partial KeyboardEventInit dictionary is an informative extension of the KeyboardEventInit dictionary, which adds charCode and keyCode members to initialize the corresponding KeyboardEvent attributes.

partial dictionary KeyboardEventInit {
  // The following support legacy user agents
  unsigned long charCode = 0;
  unsigned long keyCode = 0;
};
charCode, of type unsigned long, defaulting to 0
Initializes the charCode attribute of the KeyboardEvent to the Unicode code point for the event’s character.
keyCode, of type unsigned long, defaulting to 0
Initializes the keyCode attribute of the KeyboardEvent to the system- and implementation-dependent numerical code signifying the unmodified identifier associated with the key pressed.

7.3. Legacy key models

This section is non-normative

Implementations differ on which values are exposed on these attributes for different event types. An implementation MAY choose to expose both virtual key codes and character codes in the keyCode property (conflated model), or report separate keyCode and charCode properties (split model).

7.3.1. How to determine keyCode for keydown and keyup events

The keyCode for keydown or keyup events is calculated as follows:

7.3.2. How to determine keyCode for keypress events

The keyCode for keypress events is calculated as follows:

7.3.3. Fixed virtual key codes

The virtual key codes for the following keys do not usually change with keyboard layouts on desktop systems:

Key Virtual Key
Code
Notes
Backspace 8
Tab 9
Enter 13
Shift 16
Control 17
Alt 18
CapsLock 20
Escape 27 Esc
Space 32
PageUp 33
PageDown 34
End 35
Home 36
ArrowLeft 37
ArrowUp 38
ArrowRight 39
ArrowDown 40
Delete 46 Del

7.3.4. Optionally fixed virtual key codes

The following punctuation characters MAY change virtual codes between keyboard layouts, but reporting these values will likely be more compatible with legacy content expecting US-English keyboard layout:

Key Character Virtual Key
Code
Semicolon ";" 186
Colon ":" 186
Equals sign "=" 187
Plus "+" 187
Comma "," 188
Less than sign "<" 188
Minus "-" 189
Underscore "_" 189
Period "." 190
Greater than sign ">" 190
Forward slash "/" 191
Question mark "?" 191
Backtick "`" 192
Tilde "~" 192
Opening squace bracket "[" 219
Opening curly brace "{" 219
Backslash "\" 220
Pipe "|" 220
Closing square bracket "]" 221
Closing curly brace "}" 221
Single quote "'" 222
Double quote """ 222

8. Legacy Event Types

This section is normative. The following event types are obsolete and should only be implemented by user agents that require compatibility with legacy software.

The purpose of this section is to document the current state of these features and their relation to normative events. For implementations which do support these events, it is suggested that the definitions provided in this section be used.

The following table provides an informative summary of the event types which are deprecated in this specification. They are included here for reference and completeness.

Event Type Sync / Async Bubbling Phase Trusted event target types DOM Interface Cancelable Composed Default Action
DOMActivate Sync Yes Element UIEvent Yes Yes None
DOMFocusIn Sync Yes Window, Element FocusEvent No Yes None
DOMFocusOut Sync Yes Window, Element FocusEvent No Yes None
keypress Sync Yes Element KeyboardEvent Yes Yes Varies: launch text composition system; blur and focus events; DOMActivate event; other event
textInput Sync Yes Element TextEvent Yes Yes See definition

8.1. Legacy UIEvent events

8.1.1. Legacy UIEvent event types

8.1.1.1. DOMActivate
Type DOMActivate
Interface UIEvent
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 button, link, or other state-changing element is activated.

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

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

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

The DOMActivate event type is REQUIRED to be supported for XForms [XFORMS11], which is intended for implementation within a host language. In a scenario where a plugin or script-based implementation of XForms is intended for installation in a native implementation of this specification which does not support the DOMActivate event type, the XForms user agent has to synthesize and dispatch its own DOMActivate events based on the appropriate activation triggers.

Thus, when a click event is dispatched by a user agent conforming to UI Events, the XForms user agent has to determine whether to synthesize a DOMActivate event with the same relevant properties as a default action of that click event. Appropriate cues might be whether the click event isTrusted, or whether its event target has a DOMActivate event listener registered.

Don’t rely upon the interoperable support of DOMActivate in many user agents. Instead, the click event type should be used since it will provide more accessible behavior due to broader implementation support.

The DOMActivate event type is deprecated in this specification.

8.1.2. Activation event order

If the DOMActivate event is supported by the user agent, then the events MUST be dispatched in a set order relative to each other: (with only pertinent events listed):

Event Type Notes
1 click
2 DOMActivate default action, if supported by the user agent; synthesized; isTrusted="true"
3 All other default actions, including the activation behavior

If the focused element is activated by a key event, then the following shows the typical sequence of events (with only pertinent events listed):

Event Type Notes
1 keydown MUST be a key which can activate the element, such as the Enter or    (spacebar) key, or the element is not activated
2 click default action; synthesized; isTrusted="true"
3 DOMActivate default action, if supported by the user agent; synthesized; isTrusted="true"
4 All other default actions, including the activation behavior

8.2. Legacy FocusEvent events

8.2.1. Legacy FocusEvent event types

8.2.1.1. DOMFocusIn
Type DOMFocusIn
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 focus MUST be given to the element before the dispatch of this event type. This event type MUST be dispatched after the event type focus.

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

8.2.1.2. DOMFocusOut
Type DOMFocusOut
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 focus MUST be taken from the element before the dispatch of this event type. This event type MUST be dispatched after the event type blur.

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

8.2.2. Legacy FocusEvent event order

The following is the typical sequence of events when a focus is shifted between elements, including the deprecated DOMFocusIn and DOMFocusOut events. The order shown assumes that no element is initially focused.

Event Type Notes
User shifts focus
1 focusin Sent before first target element receives focus
2 focus Sent after first target element receives focus
3 DOMFocusIn If supported
User shifts focus
4 focusout Sent before first target element loses focus
5 focusin Sent before second target element receives focus
6 blur Sent after first target element loses focus
7 DOMFocusOut If supported
8 focus Sent after second target element receives focus
9 DOMFocusIn If supported

8.3. Legacy KeyboardEvent events

The keypress event is the traditional method for capturing key events and processing them before the DOM is updated with the effects of the key press. Code that makes use of the keypress event typically relies on the legacy charCode, keyCode, and which attributes.

Note that the keypress event is specific to key events, and has been replaced by the more general event sequence of beforeinput and input events. These new input events are not specific to keyboard actions and can be used to capture user input regardless of the original source.

8.3.1. Legacy KeyboardEvent event types

8.3.1.1. keypress
Type keypress
Interface KeyboardEvent
Sync / Async Sync
Bubbles Yes
Trusted Targets Element
Cancelable Yes
Composed Yes
Default action Varies: launch text composition system; blur and focus events; DOMActivate event; other event
Context
(trusted events)

If supported by a user agent, this event MUST be dispatched when a key is pressed down, if and only if that key normally produces a character value. The keypress event type is device dependent and relies on the capabilities of the input devices and how they are mapped in the operating system.

This event type MUST be generated after the key mapping. It MUST NOT be fired when using an input method editor.

If this event is canceled, it should prevent the input event from firing, in addition to canceling the default action.

Authors SHOULD use the beforeinput event instead of the keypress event.

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

The keypress event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type. When in editing contexts, authors can subscribe to the beforeinput event instead.

8.3.2. keypress event order

The keypress event type MUST be dispatched after the keydown event and before the keyup event associated with the same key.

The keypress event type MUST be dispatched after the beforeinput event and before the input event associated with the same key.

The sequence of key events for user-agents the support the keypress event is demonstrated in the following example:

Event Type KeyboardEvent
key
InputEvent
data
Notes
1 keydown "a"
2 beforeinput "a"
3 keypress "a"
Any default actions related to this key, such as inserting a character in to the DOM.
4 input
5 keyup "a"

8.4. Legacy TextEvent events

[Exposed=Window]
interface TextEvent : UIEvent {
    readonly attribute DOMString data;
    undefined initTextEvent(DOMString type,
        optional boolean bubbles = false,
        optional boolean cancelable = false,
        optional Window? view = null,
        optional DOMString data = "undefined");
};

See Text Event section in UI Events Algorithms for the TextEvent interface and the textInput event.

9. Extending Events

This section is non-normative

9.1. Introduction

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

9.2. Custom Events

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

A content author might have created an application which features a dynamically generated bar chart. This bar chart is meant to be updated every 5 minutes, or when a feed shows new information, or when the user refreshes it manually by clicking a button. There are several handlers that have to be called when the chart needs to be updated: the application has to fetch the most recent data, show an icon to the user that the event is being updated, and rebuild the chart. To manage this, the content author can choose to create a custom updateChart event, which is fired whenever one of the trigger conditions is met:
var chartData = ...;
var evt = document.createEvent("CustomEvent");
evt.initCustomEvent( "updateChart", true, false, { data: chartData });
document.documentElement.dispatchEvent(evt);

9.3. Implementation-Specific Extensions

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

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

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

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

9.3.1. Known Implementation-Specific Prefixes

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

Prefix Web Engine Organization
moz, Moz Gecko Mozilla
ms, MS Trident Microsoft
o, O Presto Opera Software
webkit WebKit Apple, Google, others

10. Security Considerations

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

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

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

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

11. Acknowledgements

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

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

Former editors: Tom Pixley (Netscape Communications Corporation) until July 2002; Philippe Le Hégaret (W3C) until November 2003; Björn Höhrmann (Invited Expert) until January 2008; and Jacob Rossi (Microsoft) from March 2011 to October 2011.

Contributors: In the WebApps Working Group, the following people made substantial material contributions in the process of refining and revising this specification: Bob Lund (Cable Laboratories), Cameron McCormack (Invited Expert / Mozilla), Daniel Danilatos (Google), Gary Kacmarcik (Google), Glenn Adams (Samsung), Hallvord R. M. Steen (Opera), Hironori Bono (Google), Mark Vickers (Comcast), Masayuki Nakano (Mozilla), Olli Pettay (Mozilla), Takayoshi Kochi (Google) and Travis Leithead (Microsoft).

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

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

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

12. Glossary

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

activation trigger

An event which is defined to initiate an activation behavior.

author

In the context of this specification, an author, content author, or script author is a person who writes script or other executable content that uses the interfaces, events, and event flow defined in this specification. See § 1.2.3 Content authors and content conformance category for more details.

body element

In HTML or XHTML documents, the body element represents the contents of the document. In a well-formed HTML document, the body element is a first descendant of the root element.

character value

In the context of key values, a character value is a string representing one or more Unicode characters, such as a letter or symbol, or a set of letters, each belonging to the set of valid Unicode character categories. In this specification, character values are denoted as a unicode string (e.g., U+0020) or a glyph representation of the same code point (e.g., " "), and are color coded to help distinguish these two representations.

In source code, some key values, such as non-graphic characters, can be represented using the character escape syntax of the programming language in use.

dead key

A dead key is a key or combination of keys which produces no character by itself, but which in combination or sequence with another key produces a modified character, such as a character with diacritical marks (e.g., "ö", "é", "â").

default action

A default action is an OPTIONAL supplementary behavior that an implementation MUST perform in combination with the dispatch of the event object. Each event type definition, and each specification, defines the default action for that event type, if it has one. An instance of an event MAY have more than one default action under some circumstances, such as when associated with an activation trigger. A default action MAY be cancelled through the invocation of the preventDefault() method.

delta

The estimated scroll amount (in pixels, lines, or pages) that the user agent will scroll or zoom the page in response to the physical movement of an input device that supports the WheelEvent interface (such as a mouse wheel or touch pad). The value of a delta (e.g., the deltaX, deltaY, or deltaZ attributes) is to be interpreted in the context of the current deltaMode property. The relationship between the physical movement of a wheel (or other device) and whether the delta is positive or negative is environment and device dependent. However, if a user agent scrolls as the default action then the sign of the delta is given by a right-hand coordinate system where positive X,Y, and Z axes are directed towards the right-most edge, bottom-most edge, and farthest depth (away from the user) of the document, respectively.

deprecated

Features marked as deprecated are included in the specification as reference to older implementations or specifications, but are OPTIONAL and discouraged. Only features which have existing or in-progress replacements MUST be deprecated in this specification. Implementations which do not already include support for the feature MAY implement deprecated features for reasons of backwards compatibility with existing content, but content authors creating content SHOULD NOT use deprecated features, unless there is no other way to solve a use case. Other specifications which reference this specification SHOULD NOT use deprecated features, but SHOULD point instead to the replacements of which the feature is deprecated in favor. Features marked as deprecated in this specification are expected to be dropped from future specifications.

empty string

The empty string is a value of type DOMString of length 0, i.e., a string which contains no characters (neither printing nor control characters).

event focus

Event focus is a special state of receptivity and concentration on a particular element or other event target within a document. Each element has different behavior when focused, depending on its functionality, such as priming the element for activation (as for a button or hyperlink) or toggling state (as for a checkbox), receiving text input (as for a text form field), or copying selected text. For more details, see § 3.3.3 Document Focus and Focus Context.

event focus ring

An event focus ring is an ordered set of event focus targets within a document. A host language MAY define one or more ways to determine the order of targets, such as document order, a numerical index defined per focus target, explicit pointers between focus targets, or a hybrid of different models. Each document MAY contain multiple focus rings, or conditional focus rings. Typically, for document-order or indexed focus rings, focus wraps around from the last focus target to the first.

event target

The object to which an event is targeted using the event flow. The event target is the value of the target attribute.

event type

An event type is an event object with a particular name and which defines particular trigger conditions, properties, and other characteristics which distinguish it from other event types. For example, the click event type has different characteristics than the mouseover or load event types. The event type is exposed as the type attribute on the event object. Also loosely referred to as "event", such as the click event.

host language

Any language which integrates the features of another language or API specification, while normatively referencing the origin specification rather than redefining those features, and extending those features only in ways defined by the origin specification. An origin specification typically is only intended to be implemented in the context of one or more host languages, not as a standalone language. For example, XHTML, HTML, and SVG are host languages for UI Events, and they integrate and extend the objects and models defined in this specification.

hysteresis

A feature of human interface design to accept input values within a certain range of location or time, in order to improve the user experience. For example, allowing for small deviation in the time it takes for a user to double-click a mouse button is temporal hysteresis, and not immediately closing a nested menu if the user mouses out from the parent window when transitioning to the child menu is locative hysteresis.

IME
input method editor

An input method editor (IME), also known as a front end processor, is an application that performs the conversion between keystrokes and ideographs or other characters, usually by user-guided dictionary lookup, often used in East Asian languages (e.g., Chinese, Japanese, Korean). An IME MAY also be used for dictionary-based word completion, such as on mobile devices. See § 4.3.3 Input Method Editors for treatment of IMEs in this specification. See also text composition system.

key mapping

Key mapping is the process of assigning a key value to a particular key, and is the result of a combination of several factors, including the operating system and the keyboard layout (e.g., QWERTY, Dvorak, Spanish, InScript, Chinese, etc.), and after taking into account all modifier key (Shift, Alt, et al.) and dead key states.

key value

A key value is a character value or multi-character string (such as "Enter", "Tab", or "MediaTrackNext") associated with a key in a particular state. Every key has a key value, whether or not it has a character value. This includes control keys, function keys, modifier keys, dead keys, and any other key. The key value of any given key at any given time depends upon the key mapping.

modifier key

A modifier key changes the normal behavior of a key, such as to produce a character of a different case (as with the Shift key), or to alter what functionality the key triggers (as with the Fn or Alt keys). See § 4.3.1 Modifier keys for more information about modifier keys and refer to the Modifier Keys table in [UIEvents-Key] for a list of valid modifier keys.

namespace URI

A namespace URI is a URI that identifies an XML namespace. This is called the namespace name in [XML-Names11]. See also sections 1.3.2 DOM URIs and 1.3.3 XML Namespaces regarding URIs and namespace URIs handling and comparison in the DOM APIs.

QWERTY

QWERTY (pronounced ˈkwɜrti) is a common keyboard layout, so named because the first five character keys on the top row of letter keys are Q, W, E, R, T, and Y. There are many other popular keyboard layouts (including the Dvorak and Colemak layouts), most designed for localization or ergonomics.

root element

The first element node of a document, of which all other elements are children. The document element.

rotation

An indication of incremental change on an input device using the WheelEvent interface. On some devices this MAY be a literal rotation of a wheel, while on others, it MAY be movement along a flat surface, or pressure on a particular button.

text composition system

A software component that interprets some form of alternate input (such as a input method editor, a speech processor, or a handwriting recognition system) and converts it to text.

topmost event target

The topmost event target MUST be the element highest in the rendering order which is capable of being an event target. In graphical user interfaces this is the element under the user’s pointing device. A user interface’s hit testing facility is used to determine the target. For specific details regarding hit testing and stacking order, refer to the host language.

Unicode character categories

A subset of the General Category values that are defined for each Unicode code point. This subset contains all the Letter (Ll, Lm, Lo, Lt, Lu), Number (Nd, Nl, No), Punctuation (Pc, Pd, Pe, Pf, Pi, Po, Ps) and Symbol (Sc, Sk, Sm, So) category values.

un-initialized value

The value of any event attribute (such as bubbles or currentTarget) before the event has been initialized with initEvent(). The un-initialized values of an event apply immediately after a new event has been created using the method createEvent().

Conformance

Document conventions

Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.

All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]

Examples in this specification are introduced with the words “for example” or are set apart from the normative text with class="example", like this:

This is an example of an informative example.

Informative notes begin with the word “Note” and are set apart from the normative text with class="note", like this:

Note, this is an informative note.

Conformant Algorithms

Requirements phrased in the imperative as part of algorithms (such as "strip any leading space characters" or "return false and abort these steps") are to be interpreted with the meaning of the key word ("must", "should", "may", etc) used in introducing the algorithm.

Conformance requirements phrased as algorithms or specific steps can be implemented in any manner, so long as the end result is equivalent. In particular, the algorithms defined in this specification are intended to be easy to understand and are not intended to be performant. Implementers are encouraged to optimize.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[CSS-COLOR-3]
Tantek Çelik; Chris Lilley; David Baron. CSS Color Module Level 3. 18 January 2022. REC. URL: https://www.w3.org/TR/css-color-3/
[CSS2]
Bert Bos; et al. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. 7 June 2011. REC. URL: https://www.w3.org/TR/CSS21/
[CSSOM-View]
Simon Pieters. CSSOM View Module. 17 March 2016. WD. URL: https://www.w3.org/TR/cssom-view-1/
[DOM]
Anne van Kesteren. DOM Standard. Living Standard. URL: https://dom.spec.whatwg.org/
[DOM-Level-3-Core]
Arnaud Le Hors; et al. Document Object Model (DOM) Level 3 Core Specification. 28 September 2021. REC. URL: https://www.w3.org/TR/DOM-Level-3-Core/
[HTML]
Anne van Kesteren; et al. HTML Standard. Living Standard. URL: https://html.spec.whatwg.org/multipage/
[INFRA]
Anne van Kesteren; Domenic Denicola. Infra Standard. Living Standard. URL: https://infra.spec.whatwg.org/
[PointerEvents3]
Patrick Lauke; Robert Flack. Pointer Events. 14 August 2024. WD. URL: https://www.w3.org/TR/pointerevents3/
[POINTERLOCK-2]
Mustaq Ahmed; Vincent Scheib. Pointer Lock 2.0. 17 June 2024. WD. URL: https://www.w3.org/TR/pointerlock-2/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://datatracker.ietf.org/doc/html/rfc2119
[UIEvents-Code]
Travis Leithead; Gary Kacmarcik. UI Events KeyboardEvent code Values. 30 May 2023. CR. URL: https://www.w3.org/TR/uievents-code/
[UIEvents-Key]
Travis Leithead; Gary Kacmarcik. UI Events KeyboardEvent key Values. 30 May 2023. CR. URL: https://www.w3.org/TR/uievents-key/
[WebIDL]
Edgar Chen; Timothy Gu. Web IDL Standard. Living Standard. URL: https://webidl.spec.whatwg.org/

Informative References

[DWW95]
N. Kano. Developing International Software for Windows 95 and Windows NT: A Handbook for International Software Design. 1995.
[Editing]
A. Gregor. HTML Editing APIs. URL: https://dvcs.w3.org/hg/editing/raw-file/tip/editing.html
[HTML401]
Dave Raggett; Arnaud Le Hors; Ian Jacobs. HTML 4.01 Specification. 27 March 2018. REC. URL: https://www.w3.org/TR/html401/
[HTML5]
Ian Hickson; et al. HTML5. 27 March 2018. REC. URL: https://www.w3.org/TR/html5/
[Input-Events]
Johannes Wilm. Input Events Level 1. 28 September 2023. WD. URL: https://www.w3.org/TR/input-events-1/
[PointerLock]
Vincent Scheib. Pointer Lock. 27 October 2016. REC. URL: https://www.w3.org/TR/pointerlock/
[RFC20]
V.G. Cerf. ASCII format for network interchange. October 1969. Internet Standard. URL: https://www.rfc-editor.org/rfc/rfc20
[UAAG20]
James Allan; et al. User Agent Accessibility Guidelines (UAAG) 2.0. 15 December 2015. NOTE. URL: https://www.w3.org/TR/UAAG20/
[UAX15]
Ken Whistler. Unicode Normalization Forms. 12 August 2023. Unicode Standard Annex #15. URL: https://www.unicode.org/reports/tr15/tr15-54.html
[Unicode]
The Unicode Standard. URL: https://www.unicode.org/versions/latest/
[US-ASCII]
Coded Character Set - 7-Bit American Standard Code for Information Interchange. 1986.
[WIN1252]
Windows 1252 a Coded Character Set - 8-Bit. URL: https://www.microsoft.com/globaldev/reference/sbcs/1252.htm
[XFORMS11]
John Boyer. XForms 1.1. 20 October 2009. REC. URL: https://www.w3.org/TR/xforms11/
[XML]
Tim Bray; et al. Extensible Markup Language (XML) 1.0 (Fifth Edition). 26 November 2008. REC. URL: https://www.w3.org/TR/xml/
[XML-Names11]
Tim Bray; et al. Namespaces in XML 1.1 (Second Edition). 16 August 2006. REC. URL: https://www.w3.org/TR/xml-names11/

IDL Index

[Exposed=Window]
interface UIEvent : Event {
  constructor(DOMString type, optional UIEventInit eventInitDict = {});
  readonly attribute Window? view;
  readonly attribute long detail;
};

dictionary UIEventInit : EventInit {
  Window? view = null;
  long detail = 0;
};

[Exposed=Window]
interface FocusEvent : UIEvent {
  constructor(DOMString type, optional FocusEventInit eventInitDict = {});
  readonly attribute EventTarget? relatedTarget;
};

dictionary FocusEventInit : UIEventInit {
  EventTarget? relatedTarget = null;
};

[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);
};

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;
};

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;
};

[Exposed=Window]
interface WheelEvent : MouseEvent {
  constructor(DOMString type, optional WheelEventInit eventInitDict = {});
  // DeltaModeCode
  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;
};

dictionary WheelEventInit : MouseEventInit {
  double deltaX = 0.0;
  double deltaY = 0.0;
  double deltaZ = 0.0;
  unsigned long deltaMode = 0;
};

[Exposed=Window]
interface InputEvent : UIEvent {
  constructor(DOMString type, optional InputEventInit eventInitDict = {});
  readonly attribute USVString? data;
  readonly attribute boolean isComposing;
  readonly attribute DOMString inputType;
};

dictionary InputEventInit : UIEventInit {
  DOMString? data = null;
  boolean isComposing = false;
  DOMString inputType = "";
};

[Exposed=Window]
interface KeyboardEvent : UIEvent {
  constructor(DOMString type, optional KeyboardEventInit eventInitDict = {});
  // KeyLocationCode
  const unsigned long DOM_KEY_LOCATION_STANDARD = 0x00;
  const unsigned long DOM_KEY_LOCATION_LEFT = 0x01;
  const unsigned long DOM_KEY_LOCATION_RIGHT = 0x02;
  const unsigned long DOM_KEY_LOCATION_NUMPAD = 0x03;

  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);
};

dictionary KeyboardEventInit : EventModifierInit {
  DOMString key = "";
  DOMString code = "";
  unsigned long location = 0;
  boolean repeat = false;
  boolean isComposing = false;
};

[Exposed=Window]
interface CompositionEvent : UIEvent {
  constructor(DOMString type, optional CompositionEventInit eventInitDict = {});
  readonly attribute USVString data;
};

dictionary CompositionEventInit : UIEventInit {
  DOMString data = "";
};

partial interface UIEvent {
  // Deprecated in this specification
  undefined initUIEvent(DOMString typeArg,
    optional boolean bubblesArg = false,
    optional boolean cancelableArg = false,
    optional Window? viewArg = null,
    optional long detailArg = 0);
};

partial interface MouseEvent {
  // Deprecated in this specification
  undefined initMouseEvent(DOMString typeArg,
    optional boolean bubblesArg = false,
    optional boolean cancelableArg = false,
    optional Window? viewArg = null,
    optional long detailArg = 0,
    optional long screenXArg = 0,
    optional long screenYArg = 0,
    optional long clientXArg = 0,
    optional long clientYArg = 0,
    optional boolean ctrlKeyArg = false,
    optional boolean altKeyArg = false,
    optional boolean shiftKeyArg = false,
    optional boolean metaKeyArg = false,
    optional short buttonArg = 0,
    optional EventTarget? relatedTargetArg = null);
};

partial interface KeyboardEvent {
  // Originally introduced (and deprecated) in this specification
  undefined initKeyboardEvent(DOMString typeArg,
    optional boolean bubblesArg = false,
    optional boolean cancelableArg = false,
    optional Window? viewArg = null,
    optional DOMString keyArg = "",
    optional unsigned long locationArg = 0,
    optional boolean ctrlKey = false,
    optional boolean altKey = false,
    optional boolean shiftKey = false,
    optional boolean metaKey = false);
};

partial interface CompositionEvent {
  // Originally introduced (and deprecated) in this specification
  undefined initCompositionEvent(DOMString typeArg,
    optional boolean bubblesArg = false,
    optional boolean cancelableArg = false,
    optional WindowProxy? viewArg = null,
    optional DOMString dataArg = "");
};

partial interface UIEvent {
  // The following support legacy user agents
  readonly attribute unsigned long which;
};

partial dictionary UIEventInit {
  unsigned long which = 0;
};

partial interface KeyboardEvent {
  // The following support legacy user agents
  readonly attribute unsigned long charCode;
  readonly attribute unsigned long keyCode;
};

partial dictionary KeyboardEventInit {
  // The following support legacy user agents
  unsigned long charCode = 0;
  unsigned long keyCode = 0;
};

[Exposed=Window]
interface TextEvent : UIEvent {
    readonly attribute DOMString data;
    undefined initTextEvent(DOMString type,
        optional boolean bubbles = false,
        optional boolean cancelable = false,
        optional Window? view = null,
        optional DOMString data = "undefined");
};

Issues Index

See Text Event section in UI Events Algorithms for the TextEvent interface and the textInput event.
MDN

CompositionEvent/CompositionEvent

In all current engines.

Firefox53+Safari7+Chrome26+
Opera?Edge79+
Edge (Legacy)12+IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

CompositionEvent/data

In all current engines.

Firefox9+Safari5+Chrome15+
Opera?Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari5+Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile?
MDN

CompositionEvent

In all current engines.

Firefox9+Safari5+Chrome15+
Opera?Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari5+Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

Element/auxclick_event

Firefox53+SafariNoneChrome55+
Opera?Edge79+
Edge (Legacy)?IENone
Firefox for Android53+iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

Element/blur_event

In all current engines.

Firefox24+Safari3.1+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile12.1+

Window/blur_event

In all current engines.

Firefox6+Safari5.1+Chrome5+
Opera12.1+Edge79+
Edge (Legacy)12+IE11
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

Element/click_event

In all current engines.

Firefox6+Safari3+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android6+iOS Safari1+Chrome for Android?Android WebView?Samsung Internet?Opera Mobile12.1+
MDN

Element/compositionend_event

In all current engines.

Firefox9+Safari5+Chrome15+
Opera15+Edge79+
Edge (Legacy)12+IE11
Firefox for Android?iOS Safari5+Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile14+
MDN

Element/compositionstart_event

In all current engines.

Firefox9+Safari5+Chrome15+
Opera15+Edge79+
Edge (Legacy)12+IE11
Firefox for Android?iOS Safari5+Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile14+
MDN

Element/compositionupdate_event

In all current engines.

Firefox9+Safari5+Chrome18+
Opera?Edge79+
Edge (Legacy)12+IE11
Firefox for Android?iOS Safari5+Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile?
MDN

Element/contextmenu_event

In all current engines.

Firefox6+Safari3+Chrome1+
Opera10.5+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS SafariNoneChrome for Android?Android WebView?Samsung Internet?Opera Mobile11.1+
MDN

Element/dblclick_event

In all current engines.

Firefox6+Safari3+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+IE8+
Firefox for Android6+iOS Safari1+Chrome for AndroidNoneAndroid WebView?Samsung Internet?Opera Mobile12.1+
MDN

Element/focus_event

In all current engines.

Firefox24+Safari3.1+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile12.1+

Window/focus_event

In all current engines.

Firefox6+Safari5.1+Chrome5+
Opera12.1+Edge79+
Edge (Legacy)12+IE11
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

Element/focusin_event

In all current engines.

Firefox52+Safari5+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

Element/focusout_event

In all current engines.

Firefox52+Safari5+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

Element/keydown_event

In all current engines.

Firefox6+Safari1.2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile12.1+
MDN

Element/keyup_event

In all current engines.

Firefox6+Safari1.2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile12.1+
MDN

Element/mousedown_event

In all current engines.

Firefox6+Safari4+Chrome2+
Opera11.6+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

Element/mouseenter_event

In all current engines.

Firefox10+Safari7+Chrome30+
Opera?Edge79+
Edge (Legacy)12+IE5.5+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile?
MDN

Element/mouseleave_event

In all current engines.

Firefox10+Safari7+Chrome30+
Opera?Edge79+
Edge (Legacy)12+IE5.5+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile?
MDN

Element/mousemove_event

In all current engines.

Firefox6+Safari4+Chrome2+
Opera11.6+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

Element/mouseout_event

In all current engines.

Firefox6+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

Element/mouseover_event

In all current engines.

Firefox6+Safari4+Chrome2+
Opera9.5+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile10.1+
MDN

Element/mouseup_event

In all current engines.

Firefox6+Safari4+Chrome2+
Opera11.6+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

Element/wheel_event

In all current engines.

Firefox17+Safari7+Chrome31+
Opera?Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS SafariNoneChrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

FocusEvent/FocusEvent

In all current engines.

Firefox24+Safari7+Chrome26+
Opera?Edge79+
Edge (Legacy)12+IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

FocusEvent/relatedTarget

In all current engines.

Firefox24+Safari7+Chrome26+
Opera?Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

FocusEvent

In all current engines.

Firefox24+Safari7+Chrome26+
Opera?Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

HTMLElement/beforeinput_event

In all current engines.

Firefox87+Safari10.1+Chrome60+
Opera?Edge79+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

HTMLElement/error_event

In all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile12.1+
MDN

HTMLElement/input_event

In all current engines.

Firefox6+Safari3.1+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile12+
MDN

InputEvent/InputEvent

Firefox31+SafariNoneChrome60+
Opera?Edge79+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

InputEvent/inputType

In all current engines.

Firefox66+Safari10.1+Chrome60+
Opera?Edge79+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

InputEvent/isComposing

In all current engines.

Firefox31+Safari16.4+Chrome60+
Opera?Edge79+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

InputEvent

In all current engines.

Firefox31+Safari10.1+Chrome60+
Opera?Edge79+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

KeyboardEvent/KeyboardEvent

In all current engines.

Firefox31+Safari7+Chrome26+
Opera?Edge79+
Edge (Legacy)12+IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

KeyboardEvent/altKey

In all current engines.

Firefox1.5+Safari1.2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

KeyboardEvent/code

In all current engines.

Firefox38+Safari10.1+Chrome48+
Opera?Edge79+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

KeyboardEvent/ctrlKey

In all current engines.

Firefox1.5+Safari1.2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

KeyboardEvent/getModifierState

In all current engines.

Firefox15+Safari10.1+Chrome30+
Opera?Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

KeyboardEvent/isComposing

In all current engines.

Firefox31+Safari10.1+Chrome56+
Opera?Edge79+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

KeyboardEvent/key

In all current engines.

Firefox23+Safari10.1+Chrome51+
Opera?Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

KeyboardEvent/location

In all current engines.

Firefox15+Safari8+Chrome30+
Opera?Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

KeyboardEvent/metaKey

In all current engines.

Firefox1.5+Safari1.2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

KeyboardEvent/repeat

In all current engines.

Firefox28+Safari10.1+Chrome32+
Opera?Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

KeyboardEvent/shiftKey

In all current engines.

Firefox1.5+Safari1.2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

KeyboardEvent

In all current engines.

Firefox1.5+Safari1.2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

MouseEvent/MouseEvent

In all current engines.

Firefox11+Safari7+Chrome26+
Opera?Edge79+
Edge (Legacy)12+IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

MouseEvent/altKey

In all current engines.

Firefox1.5+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

MouseEvent/button

In all current engines.

Firefox1+Safari1+Chrome1+
Opera10.6+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile11+
MDN

MouseEvent/buttons

In all current engines.

Firefox15+Safari11.1+Chrome43+
Opera?Edge79+
Edge (Legacy)12+IE9+
Firefox for Android15+iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

MouseEvent/clientX

In all current engines.

Firefox1+Safari1+Chrome1+
Opera10.6+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile11+
MDN

MouseEvent/clientY

In all current engines.

Firefox1.5+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

MouseEvent/ctrlKey

In all current engines.

Firefox1.5+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

MouseEvent/getModifierState

In all current engines.

Firefox15+Safari12.1+Chrome47+
Opera?Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

MouseEvent/metaKey

In all current engines.

Firefox1.5+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

MouseEvent/relatedTarget

In all current engines.

Firefox1.5+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

MouseEvent/screenX

In all current engines.

Firefox1.5+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

MouseEvent/screenY

In all current engines.

Firefox1.5+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

MouseEvent/shiftKey

In all current engines.

Firefox1.5+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

MouseEvent

In all current engines.

Firefox1+Safari1+Chrome1+
Opera10.6+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile11+
MDN

UIEvent/UIEvent

In all current engines.

Firefox11+Safari7+Chrome26+
Opera?Edge79+
Edge (Legacy)12+IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView1+Samsung Internet1.0+Opera Mobile?
MDN

UIEvent/detail

In all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

UIEvent/view

In all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

UIEvent

In all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

WheelEvent/WheelEvent

In all current engines.

Firefox17+Safari7+Chrome26+
Opera?Edge79+
Edge (Legacy)12+IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet1.0+Opera Mobile?
MDN

WheelEvent/deltaMode

In all current engines.

Firefox17+Safari7+Chrome26+
Opera?Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet1.0+Opera Mobile?
MDN

WheelEvent/deltaX

In all current engines.

Firefox17+Safari8+Chrome31+
Opera?Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

WheelEvent/deltaY

In all current engines.

Firefox17+Safari8+Chrome31+
Opera?Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

WheelEvent/deltaZ

In all current engines.

Firefox17+Safari8+Chrome31+
Opera?Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

WheelEvent

In all current engines.

Firefox17+Safari3+Chrome1+
Opera?Edge79+
Edge (Legacy)12+IE9+
Firefox for Android?iOS Safari1+Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile?
MDN

Window/load_event

In all current engines.

Firefox1+Safari1.3+Chrome1+
Opera4+Edge79+
Edge (Legacy)12+IE4+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile10.1+