Skip to content
jshacks.dev
Browser

JavaScript keydown Event: When It Fires and How to Use It

When the JavaScript keydown event fires, how key, code and repeat differ, modifier keys, shortcuts, IME composition and accessible keyboard handling.

8 min read
Summarize in AI
Flat illustration of one event fanning out to several listeners, with the JavaScript, Google Chrome and Node.js logos.

Keyboard handling is part of every serious interface: shortcuts, arrow-key navigation in menus and grids, Escape to close, Enter to confirm, game controls and accessibility for people who cannot use a mouse. The keydown event is where most of it happens. It fires when a key is pressed down, repeats while the key is held, and arrives before the browser has acted on the key, which is why it is the event where you can cancel the default behavior. It is also a minefield: key and code mean different things, shortcuts collide with browser and system commands, text entry is better handled with input, and international keyboards and input methods break assumptions made on a US layout. This post explains how the JavaScript keydown event works: when it fires and how it repeats, the difference between key, code and the deprecated keyCode, how to read modifier keys, how to build shortcuts and navigation safely, how to handle IME composition and shortcuts inside text fields, when to use keyup, and how to test it. It is defined in UI Events, documented on MDN, and supported in every browser.

When it fires

The event fires on the element that has keyboard focus, or on document.body when nothing does, when a key goes down. It bubbles, and it is cancelable: calling preventDefault() stops the browser's action for that key, such as typing a character, moving the caret, scrolling the page or following a link. If the user holds the key, keydown fires repeatedly, and event.repeat is true on every event after the first.

basic.jsJavaScript
document.addEventListener("keydown", (event) => {
  console.log(event.key, event.code, event.repeat);
});
Text
a KeyA false
a KeyA true
a KeyA true

The output is what holding the A key produces: the first event is not a repeat, and the following ones are. For actions that should happen once per press, such as toggling a menu, ignore repeats with if (event.repeat) return;. For actions that should continue while the key is held, such as moving a character, the repeat is useful, though repeat timing depends on the user's system settings, so a game should track key state and update on its own frame loop.

key, code and keyCode

Three properties describe the key, and they answer different questions.

PropertyMeaningExample for the Q key on a US layoutSame key on a French layout
event.keyThe character or named value the key produces"q" (or "Q" with Shift)"a"
event.codeThe physical key position"KeyQ""KeyQ"
event.keyCodeA deprecated numeric code8181

Use key when the meaning of the character matters: Escape, Enter, ArrowDown, "/", "?". Use code when the physical position matters: WASD movement in a game should work on a French keyboard where the same physical keys produce z, q, s and d. Avoid keyCode entirely, as it is deprecated and inconsistent.

keys.jsJavaScript
const moves = { KeyW: [0, -1], KeyA: [-1, 0], KeyS: [0, 1], KeyD: [1, 0] };

document.addEventListener("keydown", (event) => {
  const move = moves[event.code];
  if (move) {
    event.preventDefault();
    console.log("move", move);
  }
});

document.dispatchEvent(new KeyboardEvent("keydown", { code: "KeyD", key: "d" }));
Text
move [ 1, 0 ]

Named keys have standard strings: "Enter", "Escape", "Tab", "Backspace", "Delete", "ArrowUp", "Home", "End", "PageDown" and " " for the space bar, which is a single space character, not "Space". The key for a modifier alone is "Shift", "Control", "Alt" or "Meta", the last being Command on a Mac and the Windows key on Windows. When no real key is involved, such as with autofill or an on-screen keyboard that does not fire proper events, key can be "Unidentified".

Modifier keys

Properties shiftKey, ctrlKey, altKey and metaKey report whether each modifier is down. For a cross-platform shortcut, treat Command on macOS and Control elsewhere as the same, using a platform check.

modifiers.jsJavaScript
const isMac = /Mac|iPhone|iPad/.test(navigator.platform);

function isShortcut(event, key) {
  const mod = isMac ? event.metaKey : event.ctrlKey;
  return mod && !event.altKey && event.key.toLowerCase() === key;
}

document.addEventListener("keydown", (event) => {
  if (isShortcut(event, "k")) {
    event.preventDefault();
    console.log("open command palette");
  }
});

document.dispatchEvent(
  new KeyboardEvent("keydown", { key: "k", ctrlKey: true, metaKey: isMac }),
);
Text
open command palette

navigator.platform is deprecated but still the common check, and navigator.userAgentData?.platform is its newer counterpart where available. The isShortcut helper compares the lower-cased key, since Shift or Caps Lock changes the case, and checks that Alt is not down, which on some layouts produces different characters. Another way to read a modifier at any time is event.getModifierState("CapsLock").

Do not break the browser and the system

A shortcut you define may collide with ones the user already depends on. The browser reserves some, such as Ctrl+T, Ctrl+W and Ctrl+N, and does not let pages override them; the operating system and assistive technology reserve others; and standard editing keys inside a text field, such as Ctrl+C or the arrow keys, must keep working. Two rules keep you out of trouble. First, do not run page shortcuts while the user is typing in a field, unless the shortcut is meant to work there. Second, do not hijack a key without a clear reason, and always provide a way to see and turn off single-key shortcuts, as accessibility guidance requires, since single-character shortcuts can conflict with speech input.

typing.jsJavaScript
function isTyping(target) {
  return (
    target instanceof HTMLElement &&
    (target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName))
  );
}

document.addEventListener("keydown", (event) => {
  if (isTyping(event.target)) return;
  if (event.key === "/") {
    event.preventDefault();
    console.log("focus search");
  }
});

document.dispatchEvent(new KeyboardEvent("keydown", { key: "/" }));
Text
focus search

A / shortcut to focus the search box is common, and this guard keeps it from stealing the character from a text field. Also skip the handler if event.defaultPrevented is already true, in case another handler claimed the key.

Keyboard navigation patterns

Composite widgets, such as menus, tabs, listboxes and grids, use arrow keys to move among items, with a roving tabindex so the whole widget is one Tab stop. Put the listener on the container, so one handler covers all the items.

menu.jsJavaScript
document.body.innerHTML = `
  <ul id="menu" role="menu">
    <li role="menuitem" tabindex="0">New</li>
    <li role="menuitem" tabindex="-1">Open</li>
    <li role="menuitem" tabindex="-1">Save</li>
  </ul>
`;

const menu = document.querySelector("#menu");
const items = [...menu.querySelectorAll("[role=menuitem]")];

menu.addEventListener("keydown", (event) => {
  const index = items.indexOf(document.activeElement);
  let next = null;

  if (event.key === "ArrowDown") next = (index + 1) % items.length;
  if (event.key === "ArrowUp") next = (index - 1 + items.length) % items.length;
  if (event.key === "Home") next = 0;
  if (event.key === "End") next = items.length - 1;
  if (next === null) return;

  event.preventDefault();
  items.forEach((item, i) => (item.tabIndex = i === next ? 0 : -1));
  items[next].focus();
  console.log(items[next].textContent);
});

items[0].focus();
items[0].dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }));
Text
Open

The arrow keys wrap around, Home and End jump to the ends, and preventDefault() stops the page from scrolling. Following the pattern in the ARIA Authoring Practices Guide means screen reader users find the controls behave as they expect.

Enter and Space on custom controls

A native <button> handles Enter on keydown and Space on keyup, and fires click for both. A custom element with role="button" must reproduce that, or better, be a real button. If you do build one, handle Enter on keydown and Space on keyup, and call preventDefault() for Space so the page does not scroll.

IME composition

While a user composes text with an input method, such as typing Japanese, keydown events fire with event.isComposing true and key set to "Process" in some browsers, and keys like Enter then mean "commit the composition", not "submit". A handler that sends a chat message on Enter must check for it, or Japanese, Chinese and Korean users will send half-typed text.

ime.jsJavaScript
const box = document.createElement("textarea");
document.body.append(box);

box.addEventListener("keydown", (event) => {
  if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {
    event.preventDefault();
    console.log("send:", box.value);
  }
});

box.value = "hello";
box.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter" }));
Text
send: hello

Shift+Enter is left alone, so it inserts a newline as users expect. Safari has historically reported isComposing as false on the keydown that ends a composition, so some code also checks event.keyCode === 229, an exception to the advice to avoid keyCode.

keydown versus keypress, keyup and input

keypress is deprecated: it fired only for keys that produce characters, and inconsistently. keyup fires when the key is released, which suits "end of action" cases and the Space key on buttons. For text entry, use input or beforeinput, which cover paste, voice and autofill, and report the resulting text correctly under any layout. Do not rebuild text entry from keydown, since you would reimplement the keyboard layout, dead keys, composition and the clipboard.

Testing

In a unit test, dispatch new KeyboardEvent("keydown", { key, code, ctrlKey, bubbles: true }) on the focused element. Include bubbles: true when the handler is on an ancestor, and cancelable: true if you want to assert defaultPrevented. Testing libraries provide userEvent.keyboard("{Enter}"), which sends the whole sequence with the right order of keydown, keypress, input and keyup.

test.jsJavaScript
const event = new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true });
document.dispatchEvent(event);

console.log(event.key, event.defaultPrevented);
Text
Escape false

The result is false when no handler cancels it. Test the shortcuts with several layouts in mind by passing different key and code pairs.

Pitfalls

Using keyCode or which. Using key for physical-position controls like WASD. Running shortcuts while the user types. Forgetting event.repeat. Triggering on Enter during IME composition. Overriding browser shortcuts. Not calling preventDefault() for arrow keys in custom widgets, so the page scrolls at the same time. Shipping single-key shortcuts with no way to disable them. And relying on a keyboard-only interaction with no touch equivalent for mobile users.

Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.