Keyboard Events
There are two basic keyboard events: keydown
and keyup
. Unlike others,
keyboard events are handled on the document, not on a specific element. Keyboard
event objects belong to the KeyboardEvent
base class.
document.addEventListener("keydown", event => {
console.log("Keydown: ", event);
});
document.addEventListener("keyup", event => {
console.log("Keyup: ", event);
});
When a key is pressed, keydown
occurs first, followed by keyup
when the key
is released. In practice, basically only the keydown
event is handled, since
it happens faster than keyup
, and the user sees the key press result earlier.
The keydown
and keyup
events are triggered when any key is pressed,
including service keys (Ctrl
, Shift
, Alt
, Escape
and others).
There used to be another keyboard event called keypress
. Many forum and blog
posts may still use it, but be careful: it is obsolete and support in new
browsers may end at any time.
key
and code
properties
The key
property returns the character generated by key pressing, adjusted for
the state of modifier keys, such as Shift
, and the active language. The code
property returns the code of a physical key on the keyboard and does not depend
on languages.
document.addEventListener("keydown", event => {
console.log("key: ", event.key);
console.log("code: ", event.code);
});
Focus on the example window by clicking on it, and keyboard events will be
monitored for the document
element. Type something on the keyboard and see the
result.
Modifier keys
To handle a keyboard shortcut, for example Ctrl
+ s
or any other, the event
object has properties ctrlKey
, altKey
, shiftkey
and metaKey
, storing a
boolean value indicating whether a modifier key is pressed or not.
document.addEventListener("keydown", event => {
event.preventDefault();
if ((event.ctrlKey || event.metaKey) && event.code === "KeyS") {
console.log("«Ctrl + s» or «Command + s» combo");
}
});
Certain keyboard shortcuts may conflict with the browser default actions. For
example, Ctrl
+ d
or Command
+ d
add a bookmark. You should try to
design your page combinations so that they do not overlap with the built-in
browser combination. As a last resort, the default actions can be canceled by
calling the event.preventDefault()
method.
Not so long ago, instead of the key
and code
properties, the keyCode
property was used. Many forum and blog posts may still use it, but be careful:
it is obsolete, so do not use the keyCode
property.