KeyboardEvent objects describe a user interaction with the keyboard. Each event describes a key; the event type (keydown, keypress, or keyup) identifies what kind of activity was performed.
KeyboardEvent indicates just what's happening on a key. When you need to handle text input, use HTML5 input event instead. For example, if user inputs text from hand-writing system like tablet PC, key events may not be fired.Constructor
KeyboardEvent()- Creates a
KeyboardEventobject.
Methods
This interface also inherits methods of its parents, UIEvent and Event.
KeyboardEvent.getModifierState()- Returns a
Booleanindicating if the modifier key, like Alt, Shift, Ctrl, or Meta, was pressed when the event was created. KeyboardEvent.initKeyEvent()- Initializes a
KeyboardEventobject. This has only been implemented by Gecko (others usedKeyboardEvent.initKeyboardEvent()) and should not be used any more. The standard modern way is to use theKeyboardEvent()constructor. KeyboardEvent.initKeyboardEvent()- Initializes a
KeyboardEventobject. This has never been implemented by Gecko (who usedKeyboardEvent.initKeyEvent()) and should not be used any more. The standard modern way is to use theKeyboardEvent()constructor.
Properties
This interface also inherits properties of its parents, UIEvent and Event.
KeyboardEvent.altKeyRead only- Returns a
Booleanthat istrueif the Alt ( Option or ⌥ on OS X) key was active when the key event was generated. KeyboardEvent.charRead only- Returns a
DOMStringrepresenting the character value of the key. If the key corresponds to a printable character, this value is a non-empty Unicode string containing that character. If the key doesn't have a printable representation, this is an empty string.Note: If the key is used as a macro that inserts multiple characters, this attribute's value is the entire string, not just the first character.Warning: This has been dropped from DOM Level 3 Events. This is supported only on IE9+ and Microsoft Edge. KeyboardEvent.charCodeRead only- Returns a
Numberrepresenting the Unicode reference number of the key; this attribute is used only by thekeypressevent. For keys whosecharattribute contains multiple characters, this is the Unicode value of the first character in that attribute. In Firefox 26 this returns codes for printable characters.Warning: This attribute is deprecated; you should useKeyboardEvent.keyinstead, if available. KeyboardEvent.codeRead only- Returns a
DOMStringwith the code value of the key represented by the event. KeyboardEvent.ctrlKeyRead only- Returns a
Booleanthat istrueif the Ctrl key was active when the key event was generated. KeyboardEvent.isComposingRead only- Returns a
Booleanthat istrueif the event is fired between aftercompositionstartand beforecompositionend. KeyboardEvent.keyRead only- Returns a
DOMStringrepresenting the key value of the key represented by the event. KeyboardEvent.keyCodeRead only- Returns a
Numberrepresenting a system and implementation dependent numerical code identifying the unmodified value of the pressed key.Warning: This attribute is deprecated; you should useKeyboardEvent.keyinstead, if available. KeyboardEvent.keyIdentifierRead only- This property is non-standard and has been deprecated in favor of
KeyboardEvent.key. It was part of an old version of DOM Level 3 Events. KeyboardEvent.keyLocationRead only- This is a non-standard deprecated alias for
KeyboardEvent.location. It was part of an old version of DOM Level 3 Events. KeyboardEvent.localeRead only- Returns a
DOMStringrepresenting a locale string indicating the locale the keyboard is configured for. This may be the empty string if the browser or device doesn't know the keyboard's locale.Note: This does not describe the locale of the data being entered. A user may be using one keyboard layout while typing text in a different language. KeyboardEvent.locationRead only- Returns a
Numberrepresenting the location of the key on the keyboard or other input device. KeyboardEvent.metaKeyRead only- Returns a
Booleanthat istrueif the Meta key (on Mac keyboards, the ⌘ Command key; on Windows keyboards, the Windows key (⊞)) was active when the key event was generated. KeyboardEvent.repeatRead only- Returns a
Booleanthat istrueif the key is being held down such that it is automatically repeating. KeyboardEvent.shiftKeyRead only- Returns a
Booleanthat istrueif the Shift key was active when the key event was generated. KeyboardEvent.whichRead only- Returns a
Numberrepresenting a system and implementation dependent numeric code identifying the unmodified value of the pressed key; this is usually the same askeyCode.Warning: This attribute is deprecated; you should useKeyboardEvent.keyinstead, if available.
Notes
There are keydown, keypress, and keyup events. For most keys, Gecko dispatches a sequence of key events like this:
- When the key is first depressed, the
keydownevent is sent. - If the key is not a modifier key, the
keypressevent is sent. - When the user releases the key, the
keyupevent is sent.
Special cases
Some keys toggle the state of an indicator light; these include keys such as Caps Lock, Num Lock, and Scroll Lock. On Windows and Linux, these keys dispatch only the keydown and keyup events.
On Linux, Firefox 12 and earlier also dispatched the keypress event for these keys.
However, a limitation of the Mac OS X event model causes Caps Lock to dispatch only the keydown event. Num Lock was supported on some older laptop models (2007 models and older), but since then, Mac OS X hasn't supported Num Lock even on external keyboards. On older MacBooks with a Num Lock key, that key doesn't generate any key events. Gecko does support the Scroll Lock key if an external keyboard which has an F14 key is connected. In certain older versions of Firefox, this key generated a keypress event; this inconsistent behavior was bug 602812.
Auto-repeat handling
When a key is pressed and held down, it begins to auto-repeat. This results in a sequence of events similar to the following being dispatched:
keydownkeypresskeydownkeypress- <<repeating until the user releases the key>>
keyup
This is what the DOM Level 3 specification says should happen. There are some caveats, however, as described below.
Auto-repeat on some GTK environments such as Ubuntu 9.4
In some GTK-based environments, auto-repeat dispatches a native key-up event automatically during auto-repeat, and there's no way for Gecko to know the difference between a repeated series of keypresses and an auto-repeat. On those platforms, then, an auto-repeat key will generate the following sequence of events:
keydownkeypresskeyupkeydownkeypresskeyup- <<repeating until the user releases the key>>
keyup
In these environments, unfortunately, there's no way for web content to tell the difference between auto-repeating keys and keys that are just being pressed repeatedly.
Auto-repeat handling prior to Gecko 5.0
Before Gecko 5.0 (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2), keyboard handling was less consistent across platforms.
- Windows
- Auto-repeat behavior is the same as in Gecko 4.0 and later.
- Mac
- After the initial keydown event, only keypress events are sent until the keyup event occurs; the inter-spaced keydown events are not sent.
- Linux
- The event behavior depends on the specific platform. It will either behave like Windows or Mac depending on what the native event model does.
Note: manually firing an event does not generate the default action associated with that event. For example, manually firing a key event does not cause that letter to appear in a focused text input. In the case of UI events, this is important for security reasons, as it prevents scripts from simulating user actions that interact with the browser itself.
Example
<!DOCTYPE html>
<html>
<head>
<script>
'use strict';
document.addEventListener('keydown', (event) => {
const keyName = event.key;
if (keyName === 'Control') {
// not alert when only Control key is pressed.
return;
}
if (event.ctrlKey) {
// Even though event.key is not 'Control' (i.e. 'a' is pressed),
// event.ctrlKey may be true if Ctrl key is pressed at the time.
alert(`Combination of ctrlKey + ${keyName}`);
} else {
alert(`Key pressed ${keyName}`);
}
}, false);
document.addEventListener('keyup', (event) => {
const keyName = event.key;
// As the user release the Ctrl key, the key is no longer active.
// So event.ctrlKey is false.
if (keyName === 'Control') {
alert('Control key was released');
}
}, false);
</script>
</head>
<body>
</body>
</html>
Specifications
| Specification | Status | Comment |
|---|---|---|
| Document Object Model (DOM) Level 3 Events Specification The definition of 'KeyboardEvent' in that specification. |
Working Draft | Initial definition |
The KeyboardEvent interface specification went through numerous draft versions, first under DOM Events Level 2 where it was dropped as no consensus arose, then under DOM Events Level 3. This led to the implementation of non-standard initialization methods, the early DOM Events Level 2 version, KeyboardEvent.initKeyEvent() by Gecko browsers and the early DOM Events Level 3 version, KeyboardEvent.initKeyboardEvent() by others. Both have been superseded by the modern usage of a constructor: KeyboardEvent().
Browser compatibility
| Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
|---|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
| constructor | (Yes) | ? | 31.0 (31.0) | No support | (Yes) | ? |
.char |
No support | ? | No support | 9 | No support | No support |
.charCode |
(Yes) | ? | (Yes) | (Yes) | (Yes) | (Yes) |
.isComposing |
No support | ? | 31.0 (31.0) | No support | No support | No support |
.keyCode |
(Yes) | ? | (Yes) | (Yes) | (Yes) | (Yes) |
.locale |
No support | ? | No support | (Yes) | No support | No support |
.location |
(Yes) | ? | 15.0 (15.0) | (Yes) | No support | No support |
.repeat |
(Yes) | ? | 28.0 (28.0) | (Yes) | No support | No support |
.which |
(Yes) | ? | (Yes) | (Yes) | (Yes) | (Yes) |
.initKeyboardEvent() |
(Yes)[1] | ? | No support[2] | 9.0[3] | ? | (Yes)[1] |
| Feature | Android | Edge | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | ? | (Yes) | (Yes) | ? | ? | ? |
| constructor | ? | ? | 31.0 (31.0) | ? | ? | ? |
.char |
? | ? | No support | ? | ? | ? |
.charCode |
? | ? | (Yes) | ? | ? | ? |
.isComposing |
No support | ? | 31.0 (31.0) | No support | No support | No support |
.keyCode |
? | ? | (Yes) | ? | ? | ? |
.locale |
? | ? | No support | ? | ? | ? |
.location |
? | ? | 15.0 (15.0) | ? | ? | ? |
.repeat |
? | ? | 28.0 (28.0) | ? | ? | ? |
.which |
? | ? | (Yes) | ? | ? | ? |
.initKeyboardEvent() |
? | ? | No support | ? | ? | ? |
[1] The arguments of initKeyboardEvent() of WebKit and Blink's are different from the definition in DOM Level 3 Events. The method is: initKeyboardEvent(in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in views::AbstractView viewArg, in DOMString keyIdentifierArg, in number locationArg, in boolean ctrlKeyArg, in boolean altKeyArg, in boolean shiftKeyArg, in boolean metaKeyArg, in boolean altGraphKeyArg)
[2] Gecko won't support initKeyboardEvent() because supporting it completely breaks feature detection of web applications. See bug 999645.
[3] The argument of initKeyboardEvent() of IE is different from the definition in DOM Level 3 Events. The method is: initKeyboardEvent(in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in views::AbstractView viewArg, in DOMString keyArg, in number locationArg, in DOMString modifierListArg, in boolean repeatArt, in DOMString locationArg). See document of initKeyboardEvent() in MSDN.