Skip to content

Keyboard Events

The browser fires keydown when a key is pressed and keyup when it is released. Both are sent to the element that has focus, such as a text field, or to the body when nothing has focus, and both bubble, so a listener on document hears every key press on the page.

Use keydown for most purposes. It fires before the character appears in a text field, so the script can still cancel it, and it repeats while the key is held down. keyup suits actions that should happen once, after the user lets go.

The examples assume the script runs after the elements exist, for example from a <script> element at the end of the <body>.

The keyboard event has two properties that identify the key:

  • event.key is the value the key produces, taking the keyboard layout and the Shift key into account. Typing a capital A gives "A", and keys that produce no character have names such as "Enter", "Escape", "ArrowLeft" and "Backspace".
  • event.code names the physical key, whatever the layout. The key to the right of Tab is "KeyQ" on an English keyboard and on a French one, even though it types a on the French one.

Use key when the meaning matters, as with a shortcut letter or Enter, and use code when the position matters, as with the W, A, S and D keys used for movement in games.

<p>Press any key.</p>
<p id="last-key"></p>
const output = document.getElementById('last-key');
document.addEventListener('keydown', (event) => {
output.textContent = `key: "${event.key}", code: "${event.code}", repeat: ${event.repeat}`;
});

Pressing Shift and 3 together on a UK keyboard shows key: “£”, code: “Digit3”, and on a US keyboard the key is "#" while the code stays "Digit3". Holding a key down shows repeat: true on every event after the first.

The properties shiftKey, ctrlKey, altKey and metaKey are true when that key is held during the event. The meta key is Command on a Mac and the Windows key on Windows. A keyboard shortcut checks the modifier and the key together, and calls preventDefault() so that the browser’s own shortcut for the same keys does not also run.

<input id="search" type="search" placeholder="Search the shop">
const search = document.getElementById('search');
document.addEventListener('keydown', (event) => {
if ((event.ctrlKey || event.metaKey) && event.key === 'k') {
event.preventDefault();
search.focus();
}
if (event.key === 'Escape' && document.activeElement === search) {
search.value = '';
search.blur();
}
});

Pressing Ctrl and K, or Command and K on a Mac, moves the cursor into the search box, and pressing Escape while in the box clears it and leaves it. Some shortcuts belong to the browser or the operating system and cannot be taken over, such as Ctrl and W, which closes the tab.

Ignoring key presses meant for a text field

Section titled “Ignoring key presses meant for a text field”

A listener on document also hears keys typed into a form, so a shortcut on a single letter would fire while the user types a word that contains it. Checking where the event came from avoids that.

<label>Note <input type="text"></label>
<p id="hint">Press N for a new note.</p>
const hint = document.getElementById('hint');
document.addEventListener('keydown', (event) => {
const typing = event.target.closest('input, textarea, select, [contenteditable]');
if (typing || event.isComposing) return;
if (event.key === 'n') {
hint.textContent = 'Starting a new note';
}
});

Pressing N elsewhere on the page changes the paragraph, but typing an N into the text field does not. event.isComposing is true while the user is building a character with an input method, as when typing Japanese or Chinese, and keys pressed during that time should be left alone.

Older code identifies keys with the numeric properties keyCode, which and charCode, and listens for a third event, keypress. All of these are deprecated. The numbers differ between browsers and keyboard layouts, and keypress does not fire for keys such as the arrows or Escape. Browsers still support them so that old pages keep working, but new code should use keydown with event.key or event.code. The MDN reference for key values lists every name event.key can take.

Steve Griffith covers this topic in his video JavaScript Keyboard Events.