KeyboardEvent objects describe a user interaction with the keyboard; each event describes a single interaction between the user and a key (or combination of a key with modifier keys) on the keyboard. The event type (keydown, keypress, or keyup) identifies what kind of keyboard activity occurred.
KeyboardEvent events just indicate what interaction the user had with a key on the keyboard at a low level, providing no contextual meaning to that interaction. When you need to handle text input, use the input event instead. Keyboard events may not be fired if the user is using an alternate means of entering text, such as a handwriting system on a tablet or graphics tablet.<div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveAspectRatio="xMinYMin meet"><a xlink:href="/docs/Web/API/Event" target="_top"><rect x="1" y="1" width="75" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="38.5" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">Event</text></a><polyline points="76,25 86,20 86,30 76,25" stroke="#D4DDE4" fill="none"/><line x1="86" y1="25" x2="116" y2="25" stroke="#D4DDE4"/><a xlink:href="/docs/Web/API/UIEvent" target="_top"><rect x="116" y="1" width="75" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="153.5" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">UIEvent</text></a><polyline points="191,25 201,20 201,30 191,25" stroke="#D4DDE4" fill="none"/><line x1="201" y1="25" x2="231" y2="25" stroke="#D4DDE4"/><a xlink:href="/docs/Web/API/KeyboardEvent" target="_top"><rect x="231" y="1" width="130" height="50" fill="#F4F7F8" stroke="#D4DDE4" stroke-width="2px" /><text x="296" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">KeyboardEvent</text></a></svg></div>
a:hover text { fill: #0095DD; pointer-events: all;}
Constructor
KeyboardEvent()- Creates a new
KeyboardEventobject.
Constants
The KeyboardEvent interface defines the following constants.
Keyboard locations
The following constants identify which part of the keyboard the key event originates from. They are accessed as KeyboardEvent.DOM_KEY_LOCATION_STANDARD and so forth.
| Constant | Value | Description |
|---|---|---|
DOM_KEY_LOCATION_STANDARD |
0x00 |
The key described by the event is not identified as being located in a particular area of the keyboard; it is not located on the numeric keypad (unless it's the NumLock key), and for keys that are duplicated on the left and right sides of the keyboard, the key is, for whatever reason, not to be associated with that location. Examples include alphanumeric keys on the standard PC 101 US keyboard, the NumLock key, and the space bar. |
DOM_KEY_LOCATION_LEFT |
0x01 |
The key is one which may exist in multiple locations on the keyboard and, in this instance, is on the left side of the keyboard. Examples include the left Control key, the left Command key on a Macintosh keyboard, or the left Shift key. |
DOM_KEY_LOCATION_RIGHT |
0x02 |
The key is one which may exist in multiple positions on the keyboard and, in this case, is located on the right side of the keyboard. Examples include the right Shift key and the right Alt key (Option on a Mac keyboard). |
DOM_KEY_LOCATION_NUMPAD |
0x03 |
The key is located on the numeric keypad, or is a virtual key associated with the numeric keypad if there's more than one place the key could originate from. The NumLock key does not fall into this group and is always encoded with the location Examples include the digits on the numeric keypad, the keypad's Enter key, and the decimal point on the keypad. |
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.codeRead only- Returns a
DOMStringwith the code value of the physical key represented by the event.Warning: This ignores the user's keyboard layout, so that if the user presses the key at the "Y" position in a QWERTY keyboard layout (near the middle of the row above the home row), this will always return "KeyY", even if the user has a QWERTZ keyboard (which would mean the user expects a "Z" and all the other properties would indicate a "Z") or a Dvorak keyboard layout (where the user would expect an "F"). 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.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. A list of the constants identifying the locations is shown above in Keyboard locations. 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.
Methods
This interface also inherits methods of its parents, UIEvent and Event.
KeyboardEvent.getModifierState()- Returns a
Booleanindicating if a modifier key such as Alt, Shift, Ctrl, or Meta, was pressed when the event was created.
Obsolete methods
KeyboardEvent.initKeyEvent()- Initializes a
KeyboardEventobject. This was implemented only by Firefox, and is no longer supported even there; instead, you should use theKeyboardEvent()constructor. KeyboardEvent.initKeyboardEvent()- Initializes a
KeyboardEventobject. This is now deprecated. You should instead use theKeyboardEvent()constructor.
Obsolete properties
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. 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.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.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.
Events
The following events are based on the KeyboardEvent type. They can be delivered to any object which implements GlobalEventHandlers, including Element, Document, and Window. In the list below, each event links to the documentation for the Document handler for the event, which applies generally to all of the recipients.
Obsolete events
keypress- A key that normally produces a character value has been pressed. This event was highly device-dependent and is obsolete. You should not use it.
Usage notes
There are three types of keyboard events: keydown, keypress, and keyup. For most keys, Gecko dispatches a sequence of key events like this:
- When the key is first pressed, 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 macOS 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, macOS 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') {
// do not alert when only Control key is pressed.
return;
}
if (event.ctrlKey) {
// Even though event.key is not 'Control' (e.g., 'a' is pressed),
// event.ctrlKey may be true if Ctrl key is pressed at the same time.
alert(`Combination of ctrlKey + ${keyName}`);
} else {
alert(`Key pressed ${keyName}`);
}
}, false);
document.addEventListener('keyup', (event) => {
const keyName = event.key;
// As the user releases 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 |
|---|---|---|
| UI Events The definition of 'KeyboardEvent' in that specification. |
Working Draft |
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
| Desktop | Mobile | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
KeyboardEvent | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1.5 | IE Full support 9 | Opera Full support 12.1 | Safari Full support 3.1 | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 12.1 | Safari iOS Full support 2 | Samsung Internet Android Full support 1.0 |
DOM_KEY_LOCATION_LEFT | Chrome Full support Yes | Edge Full support ≤18 | Firefox Full support Yes | IE ? | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
DOM_KEY_LOCATION_NUMPAD | Chrome Full support Yes | Edge Full support ≤18 | Firefox Full support Yes | IE ? | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
DOM_KEY_LOCATION_RIGHT | Chrome Full support Yes | Edge Full support ≤18 | Firefox Full support Yes | IE ? | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
DOM_KEY_LOCATION_STANDARD | Chrome Full support Yes | Edge Full support ≤18 | Firefox Full support Yes | IE ? | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
KeyboardEvent() constructor | Chrome Full support Yes | Edge Full support ≤79 | Firefox Full support 31 | IE No support No | Opera Full support Yes | Safari ? | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support 31 | Opera Android Full support Yes | Safari iOS ? | Samsung Internet Android Full support Yes |
altKey | Chrome Full support Yes | Edge Full support 12 | Firefox Full support Yes | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
charCode | Chrome Full support 26 | Edge Full support 12 | Firefox Full support 3 | IE Full support 9 | Opera Full support 12.1 | Safari Full support 5.1 | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support 5.1 | Samsung Internet Android Full support Yes |
code | Chrome Full support 48 | Edge Full support 79 | Firefox Full support 38 | IE No support No | Opera Full support 35 | Safari Full support 10 | WebView Android Full support 48 | Chrome Android Full support 48 | Firefox Android Full support 38 | Opera Android Full support 35 | Safari iOS Full support 10 | Samsung Internet Android Full support 5.0 |
ctrlKey | Chrome Full support Yes | Edge Full support 12 | Firefox Full support Yes | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
getModifierState | Chrome Full support 31 | Edge Full support 12 | Firefox Full support 15 | IE Full support 9 | Opera Full support 17 | Safari Full support 10.1 | WebView Android Full support 4.4.3 | Chrome Android Full support 31 | Firefox Android Full support 15 | Opera Android Full support 18 | Safari iOS Full support 10.3 | Samsung Internet Android Full support 2.0 |
isComposing | Chrome Full support 56 | Edge Full support ≤79 | Firefox Full support 31 | IE No support No | Opera Full support 43 | Safari Full support 10.1 | WebView Android Full support 56 | Chrome Android Full support 56 | Firefox Android Full support 31 | Opera Android Full support 43 | Safari iOS Full support 10.3 | Samsung Internet Android Full support 6.0 |
key | Chrome Full support 51 | Edge Full support 12 | Firefox Full support 23 | IE
Full support
9
| Opera Full support 38 | Safari Full support 10 | WebView Android Full support 51 | Chrome Android Full support 51 | Firefox Android Full support 23 | Opera Android Full support 41 | Safari iOS Full support 10 | Samsung Internet Android Full support 5.0 |
keyCode | Chrome Full support 26 | Edge Full support 12 | Firefox Full support 3 | IE Full support 9 | Opera Full support 12.1 | Safari Full support 5 | WebView Android Full support ≤37 | Chrome Android Full support 26 | Firefox Android Full support 4 | Opera Android Full support 12.1 | Safari iOS Full support 5.1 | Samsung Internet Android Full support 1.5 |
keyIdentifier | Chrome No support 26 — 54 | Edge ? | Firefox No support No | IE No support No | Opera No support 15 — 41 | Safari Full support 5.1 | WebView Android No support ? — 54 | Chrome Android No support 26 — 54 | Firefox Android No support No | Opera Android No support ? — 41 | Safari iOS Full support 5.1 | Samsung Internet Android No support 1.5 — 6.0 |
location | Chrome Full support Yes | Edge Full support 12 | Firefox Full support 15 | IE Full support 9 | Opera Full support Yes | Safari Full support 6.1 | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support 15 | Opera Android Full support Yes | Safari iOS Full support 8 | Samsung Internet Android Full support Yes |
metaKey | Chrome Full support Yes | Edge Full support 12 | Firefox Full support Yes | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
repeat | Chrome Full support Yes | Edge Full support 79 | Firefox Full support 28 | IE No support No | Opera Full support Yes | Safari Full support 10.1 | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support 28 | Opera Android Full support Yes | Safari iOS Full support 10.3 | Samsung Internet Android Full support Yes |
shiftKey | Chrome Full support Yes | Edge Full support 12 | Firefox Full support Yes | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
which | Chrome Full support 4 | Edge Full support 12 | Firefox
Full support
2
| IE Full support 9 | Opera Full support 12.1 | Safari Full support 5.1 | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android
Full support
Yes
| Opera Android Full support 12.1 | Safari iOS Full support 5.1 | Samsung Internet Android Full support Yes |
Legend
- Full support
- Full support
- No support
- No support
- Compatibility unknown
- Compatibility unknown
- Non-standard. Expect poor cross-browser support.
- Non-standard. Expect poor cross-browser support.
- Deprecated. Not for use in new websites.
- Deprecated. Not for use in new websites.
- See implementation notes.
- See implementation notes.
Compatibility notes
- As of Firefox 65, the
keypressevent is no longer fired for non-printable keys (bug 968056), except for the Enter key, and the Shift + Enter and Ctrl + Enter key combinations (these were kept for cross-browser compatibility purposes).
