Keyboard Events

Editor’s Draft,

More details about this document
This version:
https://w3c.github.io/uievents/
Latest published version:
https://www.w3.org/TR/uievents/
Feedback:
GitHub
Editors:
(Google)
(Microsoft)
Former Editor:
Doug Schepers (Mar 2008 - May 2011)
Tests:
web-platform-tests uievents/ (ongoing work)

Abstract

*** Keyboard Events ***

Note: This is an experimental split of the UI Events spec into smaller, event-specific specs. The split was made from an out-of-date snapshot, so the information here is not current, so please focus on the overall structure rather than the specifics of the content. If this experiment goes well, then we will split the current spec after all outstanding pull requests have been handled.

Status of this document

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

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

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

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

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

This document is governed by the 2 November 2021 W3C Process Document.

1. Introduction

1.1. Overview

TODO.

1.2. Conformance

Boilerplate?

2. Stylistic Conventions

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

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

And finally:

This is a note.

This is an open issue.

This is a warning.

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

3. 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.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.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.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.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.3. 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.4. Keyboard Event Types

3.4.1. keydown

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

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

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

If this event is canceled, the associated event types MUST NOT be dispatched, and the associated actions MUST NOT be performed.

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

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

4. Keyboard events and key values

This section contains necessary information regarding keyboard events:

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

4.1. Keyboard Input

This section is non-normative

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

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

4.1.1. Key Legends

This section is informative

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

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

4.2. Key codes

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

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

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

4.2.1. Motivation for the code Attribute

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

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

4.2.2. The Relationship Between key and code

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

4.2.3. code Examples

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

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

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

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

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

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

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

Sequence of Keyboard Events : Shift and 2

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

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

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

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

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

4.2.4. code and Virtual Keyboards

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

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

4.3. Keyboard Event key Values

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

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

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

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

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

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

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

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

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

4.3.1. Modifier keys

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

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

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

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

4.3.2. Dead keys

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

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

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

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

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

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

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

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

4.3.3. Input Method Editors

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

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

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

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

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

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

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

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

4.3.3.1. Input Method Editor mode keys

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

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

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

4.3.4. Default actions and cancelable keyboard events

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

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

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

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

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

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

5. Constructing Mouse and Keyboard Events

Generally, when a constructor of an Event interface, or of an interface inherited from the Event interface, is invoked, the steps described in [DOM] should be followed. However the KeyboardEvent and MouseEvent interfaces provide additional dictionary members for initializing the internal state of the Event object’s key modifiers: specifically, the internal state queried for using the getModifierState() and getModifierState() methods. This section supplements the DOM4 steps for intializing a new Event object with these optional modifier states.

For the purposes of constructing a KeyboardEvent, MouseEvent, or object derived from these objects using the algorithm below, all KeyboardEvent, MouseEvent, and derived objects have internal key modifier state which can be set and retrieved using the key modifier names described in the Modifier Keys table in [UIEvents-Key].

The following steps supplement the algorithm defined for constructing events in DOM4:

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 MutationEvent requires calls to two initializer methods: initEvent and initMutationEvent.

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

6.1. Initializers for interface KeyboardEvent

This section is informative

The argument list to this legacy KeyboardEvent initializer does not include the detailArg (present in other initializers) and adds the locale argument (see § 9.3.1 Changes between different drafts of UI Events); 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.

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.

7.1. 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.1.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.2 Legacy key models for more details on how to determine the values for keyCode.

7.1.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.2. 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.2.1. How to determine keyCode for keydown and keyup events

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

7.2.2. How to determine keyCode for keypress events

The keyCode for keypress events is calculated as follows:

7.2.3. Fixed virtual key codes

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

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

7.2.4. Optionally fixed virtual key codes

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

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

8. Legacy Event Types

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

8.1. Legacy KeyboardEvent events

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

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

8.1.1. Legacy KeyboardEvent event types

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

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

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

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

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

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

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

8.1.2. keypress event order

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

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

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

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

9. Other UIEvents [DELETE]

This section will be deleted.

Temporary place to "define" other referenced UI Events (to make the bikeshed linker happy). This will be deleted once we have proper cross-references.

beforeinput blur click compositionend compositionstart compositionupdate DOMActivate input

9.1. Things defined in other sections

9.1.1. Activation triggers and behavior

9.1.2. Default actions and cancelable events

9.1.3. Event dispatch and DOM event flow

9.1.4. Focus Events

9.1.5. Web browsers and other dynamic or interactive user agents

9.1.6. Authoring tools

9.2. Things defined in CompositionEvents

9.2.1. Composition Events

9.3. Things defined in Changes

9.3.1. Changes between different drafts of UI Events

10. Glossary [DELETE]

This section will be deleted.

Temporary glossary terms (for bikeshed linker). Many of these are properly defined elsewhere and should be linked to directly. Terms which should be defined in this spec should be defined inline.

activation behavior

The action taken when an event, typically initiated by users through an input device, causes an element to fulfill a defined task. The task MAY be defined for that element by the host language, or by author-defined variables, or both. The default task for any given element MAY be a generic action, or MAY be unique to that element. For example, the activation behavior of an HTML or SVG <a> element is to cause the user agent to traverse the link specified in the href attribute, with the further optional parameter of specifying the browsing context for the traversal (such as the current window or tab, a named window, or a new window). The activation behavior of an HTML <input> element with the type attribute value submit is be to send the values of the form elements to an author-defined IRI by the author-defined HTTP method. See § 9.1.1 Activation triggers and behavior for more details.

activation trigger

An event which is defined to initiate an activation behavior. Refer to § 9.1.1 Activation triggers and behavior for more details.

body element

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

character value

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

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

dead key

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

default action

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

deprecated

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

empty string

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

event

An event is the representation of some occurrence (such as a mouse click on the presentation of an element, the removal of child node from an element, or any number of other possibilities) which is associated with its event target. Each event is an instantiation of one specific event type.

event target

The object to which an event is targeted using the § 9.1.3 Event dispatch and DOM event flow. The event target is the value of the target attribute.

host language

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

IME
input method editor

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

key mapping

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

key value

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

modifier key

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

QWERTY

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

text composition system

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

Unicode character categories

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

un-initialized value

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

user agent

A program, such as a browser or content authoring tool, normally running on a client machine, which acts on a user’s behalf in retrieving, interpreting, executing, presenting, or creating content. Users MAY act on the content using different user agents at different times, for different purposes. See the § 9.1.5 Web browsers and other dynamic or interactive user agents and § 9.1.6 Authoring tools for details on the requirements for a conforming user agent.

Window

The Window is the object referred to by the current document’s browsing context’s Window Proxy object as defined in HTML5 [HTML5].

Conformance

Document conventions

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

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

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

This is an example of an informative example.

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

Note, this is an informative note.

Conformant Algorithms

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

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

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[CSS-DISPLAY-4]
CSS Display Module Level 4 URL: https://drafts.csswg.org/css-display-4/
[CSS21]
Bert Bos; et al. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. URL: https://drafts.csswg.org/css2/
[DOM]
Anne van Kesteren. DOM Standard. Living Standard. URL: https://dom.spec.whatwg.org/
[HTML]
Anne van Kesteren; et al. HTML Standard. Living Standard. URL: https://html.spec.whatwg.org/multipage/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://datatracker.ietf.org/doc/html/rfc2119
[UIEVENTS]
Gary Kacmarcik; Travis Leithead. UI Events. URL: https://w3c.github.io/uievents/
[UIEvents-Code]
Gary Kacmarcik; Travis Leithead. UI Events KeyboardEvent code Values. URL: https://w3c.github.io/uievents-code/
[UIEvents-Key]
Gary Kacmarcik; Travis Leithead. UI Events KeyboardEvent key Values. URL: https://w3c.github.io/uievents-key/
[WEBDRIVER-BIDI]
WebDriver BiDi URL: https://w3c.github.io/webdriver-bidi/
[WEBIDL]
Edgar Chen; Timothy Gu. Web IDL Standard. Living Standard. URL: https://webidl.spec.whatwg.org/

Informative References

[DWW95]
N. Kano. Developing International Software for Windows 95 and Windows NT: A Handbook for International Software Design. 1995.
[HTML5]
Ian Hickson; et al. HTML5. URL: https://www.w3.org/html/wg/drafts/html/master/
[RFC20]
V.G. Cerf. ASCII format for network interchange. October 1969. Internet Standard. URL: https://www.rfc-editor.org/rfc/rfc20
[US-ASCII]
Coded Character Set - 7-Bit American Standard Code for Information Interchange. 1986.
[WIN1252]
Windows 1252 a Coded Character Set - 8-Bit. URL: https://www.microsoft.com/globaldev/reference/sbcs/1252.htm

IDL Index

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

  readonly attribute DOMString key;
  readonly attribute DOMString code;
  readonly attribute unsigned long location;

  readonly attribute boolean ctrlKey;
  readonly attribute boolean shiftKey;
  readonly attribute boolean altKey;
  readonly attribute boolean metaKey;

  readonly attribute boolean repeat;
  readonly attribute boolean isComposing;

  boolean getModifierState(DOMString keyArg);
};

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

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

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

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