KeyboardEvent

KeyboardEventobjects 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,orkeyup) identifies what kind of keyboard activity occurred.

Note:KeyboardEventevents 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 theinputevent 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.

Event UIEvent KeyboardEvent

Constructor

KeyboardEvent()

Creates a newKeyboardEventobject.

Constants

TheKeyboardEventinterface defines the following constants.

Keyboard locations

The following constants identify which part of the keyboard the key event originates from. They are accessed asKeyboardEvent.DOM_KEY_LOCATION_STANDARDand so forth.

Keyboard location identifiers
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 Alpha numeric 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 DOM_KEY_LOCATION_STANDARD.

Examples include the digits on the numeric keypad, the keypad's Enter key, and the decimal point on the keypad.

Instance properties

This interface also inherits properties of its parents,UIEventandEvent.

KeyboardEvent.altKeyRead only

Returns a boolean value that istrueif theAlt(Optionoron macOS) key was active when the key event was generated.

KeyboardEvent.codeRead only

Returns a string with 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" ). If you want to display the correct keystrokes to the user, you can useKeyboard.getLayoutMap().

KeyboardEvent.ctrlKeyRead only

Returns a boolean value that istrueif theCtrlkey was active when the key event was generated.

KeyboardEvent.isComposingRead only

Returns a boolean value that istrueif the event is fired between aftercompositionstartand beforecompositionend.

KeyboardEvent.keyRead only

Returns a string representing the key value of the key represented by the event.

KeyboardEvent.locationRead only

Returns a number representing the location of the key on the keyboard or other input device. A list of the constants identifying the locations is shown above inKeyboard locations.

KeyboardEvent.metaKeyRead only

Returns a boolean value that istrueif theMetakey (on Mac keyboards, the⌘ Commandkey; on Windows keyboards, the Windows key ()) was active when the key event was generated.

KeyboardEvent.repeatRead only

Returns a boolean value that istrueif the key is being held down such that it is automatically repeating.

KeyboardEvent.shiftKeyRead only

Returns a boolean value that istrueif theShiftkey was active when the key event was generated.

Obsolete properties

KeyboardEvent.charCode Deprecated Read only

Returns a number representing the Unicode reference number of the key; this property is used only by thekeypressevent. For keys whosecharproperty contains multiple characters, this is the Unicode value of the first character in that property. In Firefox 26 this returns codes for printable characters.

KeyboardEvent.keyCode Deprecated Read only

Returns a number representing a system and implementation dependent numerical code identifying the unmodified value of the pressed key.

KeyboardEvent.keyIdentifier Non-standard Deprecated Read only

This property is non-standard and has been deprecated in favor ofKeyboardEvent.key.It was part of an old version of DOM Level 3 Events.

Instance methods

This interface also inherits methods of its parents,UIEventandEvent.

KeyboardEvent.getModifierState()

Returns a boolean value indicating if a modifier key such asAlt,Shift,Ctrl,orMeta,was pressed when the event was created.

Obsolete methods

KeyboardEvent.initKeyEvent() Deprecated

Initializes aKeyboardEventobject. This was implemented only by Firefox, and is no longer supported even there; instead, you should use theKeyboardEvent()constructor.

KeyboardEvent.initKeyboardEvent() Deprecated

Initializes aKeyboardEventobject. This is now deprecated. You should instead use theKeyboardEvent()constructor.

Events

The following events are based on theKeyboardEventtype. In the list below, each event links to the documentation for theElementhandler for the event, which applies generally to all of the recipients, includingElement,Document,andWindow.

keydown

A key has been pressed.

keyup

A key has been released.

Obsolete events

keypress Deprecated

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,andkeyup.For most keys, Gecko dispatches a sequence of key events like this:

  1. When the key is first pressed, thekeydownevent is sent.
  2. If the key is not a modifier key, thekeypressevent is sent.
  3. When the user releases the key, thekeyupevent 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 thekeydownandkeyupevents.

Note:On Linux, Firefox 12 and earlier also dispatched thekeypressevent for these keys.

However, a limitation of the macOS event model causes Caps Lock to dispatch only thekeydownevent. 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 akeypressevent; this inconsistent behavior wasFirefox 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:

  1. keydown
  2. keypress
  3. keydown
  4. keypress
  5. <<repeating until the user releases the key>>
  6. 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:

  1. keydown
  2. keypress
  3. keyup
  4. keydown
  5. keypress
  6. keyup
  7. <<repeating until the user releases the key>>
  8. 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.

Example

js
document.addEventListener(
"keydown",
(event)=>{
constkeyName=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)=>{
constkeyName=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,
);

Specifications

Specification
UI Events
#interface-keyboardevent

TheKeyboardEventinterface 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

BCD tables only load in the browser

Compatibility notes

  • As of Firefox 65, thekeypressevent is no longer fired fornon-printable keys(Firefox bug 968056), except for the Enter key, and the Shift + Enter and Ctrl + Enter key combinations (these were kept for cross-browser compatibility purposes).

See also