Xiaoqian Wu (W3C) · w3.org

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.1.1. Mouse and Wheel Events

The Mouse Events and Wheel Events section of this specification have been moved to the Pointer Events specification [pointerevents4].

1.2. Conformance

This section is normative.

Within this specification, the key words MUST, MUST NOT, REQUIRED, SHALL, SHALL NOT, SHOULD, SHOULD NOT, RECOMMENDED, MAY, and OPTIONAL are to be interpreted as described in [RFC2119].

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

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

1.2.1. Web browsers and other dynamic or interactive user agents

A dynamic or interactive user agent, referred to here as a browser (be it a Web browser, AT (Accessibility Technology) application, or other similar program), conforms to UI Events if it supports:

  • the Core module defined in [DOM-Level-3-Core]

  • all the interfaces and events with their associated methods, attributes, and semantics defined in this specification with the exception of those marked as deprecated (a conforming user agent MAY implement the deprecated interfaces, events, or APIs for backwards compatibility, but is not required to do so in order to be conforming)

  • the complete set of key and code values defined in [UIEvents-Key] and [UIEvents-Code] (subject to platform availability), and

  • all other normative requirements defined in this specification.

A conforming browser MUST dispatch events appropriate to the given EventTarget when the conditions defined for that event type have been met.

A browser conforms specifically to UI Events if it implements the interfaces and related event types specified in this document.

A conforming browser MUST support scripting, declarative interactivity, or some other means of detecting and dispatching events in the manner described by this specification, and MUST support the APIs specified for that event type.

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

A conforming browser MAY also support features not found in this specification, but which use the interfaces, events, or other features defined in this specification, and MAY implement additional interfaces and event types appropriate to that implementation. Such features can be later standardized in future specifications.

A browser which does not conform to all required portions of this specification MUST NOT claim conformance to UI Events. Such an implementation which does conform to portions of this specification MAY claim conformance to those specific portions.

A conforming browser MUST also be a conforming implementation of the IDL fragments in this specification, as described in the Web IDL specification [WebIDL].

1.2.2. Authoring tools

A content authoring tool conforms to UI Events if it produces content which uses the event types, consistent in a manner as defined in this specification.

A content authoring tool MUST NOT claim conformance to UI Events for content it produces which uses features of this specification marked as deprecated in this specification.

A conforming content authoring tool SHOULD provide to the content author a means to use all event types and interfaces appropriate to all host languages in the content document being produced.

1.2.3. Content authors and content

A content author creates conforming UI Events content if that content uses the event types consistent in a manner as defined in this specification.

A content author SHOULD NOT use features of this specification marked as deprecated, but SHOULD rely instead upon replacement mechanisms defined in this specification and elsewhere.

Conforming content MUST use the semantics of the interfaces and event types as described in this specification.

Content authors are advised to follow best practices as described in accessibility and internationalization guideline specifications.

1.2.4. Specifications and host languages

A specification or host language conforms to UI Events if it references and uses the event flow mechanism, interfaces, events, or other features defined in [DOM], and does not extend these features in incompatible ways.

A specification or host language conforms specifically to UI Events if it references and uses the interfaces and related event types specified in this document. A conforming specification MAY define additional interfaces and event types appropriate to that specification, or MAY extend the UI Events interfaces and event types in a manner that does not contradict or conflict with the definitions of those interfaces and event types in this specification.

Specifications or host languages which reference UI Events SHOULD NOT use or recommend features of this specification marked as deprecated, but SHOULD use or recommend the indicated replacement for that the feature (if available).

2. Stylistic Conventions

This specification follows the Proposed W3C Specification Conventions, with the following supplemental additions:

  • The key cap printed on a key is shown as , = or Q. This is used to refer to a key from the user’s perspective without regard for the key and code values in the generated KeyboardEvent.

  • Glyphs representing character are shown as: "𣧂".

  • Unicode character encodings are shown as: U+003d.

  • Names of key values generated by a key press (i.e., the value of KeyboardEvent.key) are shown as: "ArrowDown", "=", "q" or "Q".

  • Names of key codes associated with the physical keys (i.e., the value of KeyboardEvent.code) are shown as: "ArrowDown", "Equal" or "KeyQ".

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

And finally:

This is a note.

This is an open issue.

This is a warning.

interface Example {
    // This is an IDL definition.
};

3. Basic Event Interfaces

The basic event interfaces defined in [DOM] are fundamental to UI Events. These basic event interfaces MUST always be supported by the implementation:

The event 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
beforeinput Sync Yes Element InputEvent Yes Update the DOM element
blur Sync No Window, Element FocusEvent No None
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
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
select Sync Yes Element Event No None
unload Sync No Window, Document, Element Event No None

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 ? ;
};
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 ?  =  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 operating system focus context which MAY be on one of many different applications currently running on the computer. One of these applications with focus can be a browser.

  • When the browser has focus, the user can switch (such as with the tab key) the application focus context among the different browser user interface fields (e.g., the Web site location bar, a search field, etc.). One of these user interface fields can be the document being shown in a tab.

  • When the document itself has focus, the document focus context can be set to any of the focusable elements in the document.

The event types defined in this specification deal exclusively with document focus, and the event target identified in the event details MUST only be part of the document or documents in the window, never a part of the browser or operating system, even when switching from one focus context to another.

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

3.3.4. Focus Event Types

The Focus event types are listed below.

3.3.4.1. blur
Type blur
Interface FocusEvent
Sync / Async Sync
Bubbles No
Trusted Targets Window, Element
Cancelable No
Composed Yes
Default action None
Context
(trusted events)

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

3.3.4.2. focus
Type focus
Interface FocusEvent
Sync / Async Sync
Bubbles No
Trusted Targets Window, Element
Cancelable No
Composed Yes
Default action None
Context
(trusted events)

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

3.3.4.3. focusin
Type focusin
Interface FocusEvent
Sync / Async Sync
Bubbles Yes
Trusted Targets Window, Element
Cancelable No
Composed Yes
Default action None
Context
(trusted events)

A user agent MUST dispatch this event when an event target receives focus. The event target MUST be the element which received focus. The focus event MUST fire before the dispatch of this event type. This event type is similar to focus, but does bubble.

3.3.4.4. focusout
Type focusout
Interface FocusEvent
Sync / Async Sync
Bubbles Yes
Trusted Targets Window, Element
Cancelable No
Composed Yes
Default action None
Context
(trusted events)

A user agent MUST dispatch this event when an event target loses focus. The event target MUST be the element which lost focus. The blur event MUST fire before the dispatch of this event type. This event type is similar to blur, but does bubble.

3.4. 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.4.1. Interface InputEvent

3.4.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.4.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.4.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.4.3. Input Event Types

3.4.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.4.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.5. 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.5.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.5.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.5.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.5.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.5.3. 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 mouse events using this dictionary are defined in the [pointerevents4] specification.

 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.5.4. KeyboardEvent Algorithms

3.5.4.1. Global State for KeyboardEvent
3.5.4.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.5.5. 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.5.6. Keyboard Event Types

3.5.6.1. keydown
Type keydown
Interface KeyboardEvent
Sync / Async Sync
Bubbles Yes
Trusted Targets Element
Cancelable Yes
Composed Yes
Default action Varies: beforeinput and input events; launch text composition system; blur and focus events; keypress event (if supported); activation behavior; other event
Context
(trusted events)

A user agent MUST dispatch this event when a key is pressed down. The keydown event type is device dependent and relies on the capabilities of the input devices and how they are mapped in the operating system. This event type MUST be generated after the key mapping. This event type MUST be dispatched before the beforeinput, input, and keyup events associated with the same key.

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

  • If the key is associated with a character, the default action MUST be to dispatch a beforeinput event followed by an input event. In the case where the key which is associated with multiple characters (such as with a macro or certain sequences of dead keys), the default action MUST be to dispatch one set of beforeinput / input events for each character

  • If the key is associated with a text composition system, the default action MUST be to launch that system

  • If the key is the Tab key, the default action MUST be to shift the document focus from the currently focused element (if any) to the new focused element, as described in Focus Event Types

  • If the key is the Enter or   (Space) key and the current focus is on a state-changing element, the default action MUST be to dispatch a click event, and a DOMActivate event if that event type is supported by the user agent.

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.5.6.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.6. 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.6.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.6.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.6.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.6.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.6.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.6.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.6.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.6.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.6.7. Composition Event Types

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

  • Explanation of keyboard layout, mapping, and key values.

  • Relations between keys, such as dead keys or modifiers keys.

  • Relations between keyboard events and their default actions.

  • The set of key values, and guidelines on how to extend this set.

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:

  • Mechanical layout: the dimensions, size, and placement of the physical keys on the keyboard

  • Visual markings: the labels (or legends) that mark each key

  • Functional mapping: the abstract key-value association of each key.

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

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

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

  • Read the virtual key code from the operating system’s event information, if such information is available.

  • If an Input Method Editor is processing key input and the event is keydown, return 229.

  • If input key when pressed without modifiers would insert a numerical character (0-9), return the ASCII code of that numerical character.

  • If input key when pressed without modifiers would insert a lower case character in the a-z alphabetical range, return the ASCII code of the upper case equivalent.

  • If the implementation supports a key code conversion table for the operating system and platform, look up the value. If the conversion table specifies an alternate virtual key value for the given input, return the specified value.

  • If the key’s function, as determined in an implementation-specific way, corresponds to one of the keys in the § 7.3.3 Fixed virtual key codes table, return the corresponding key code.

  • Return the virtual key code from the operating system.

  • If no key code was found, return 0.

7.3.2. How to determine keyCode for keypress events

The keyCode for keypress events is calculated as follows:

  • If the implementation supports a conflated model, set keyCode to the Unicode code point of the character being entered.

  • If the implementation supports a split model, set "https://

Read the original on w3.org ↗