Skip to content
jshacks.dev
Browser

How to Make Keyboard Shortcuts in JavaScript

Make keyboard shortcuts in JavaScript with keydown, event.key and modifiers, a registry, input field guards, cross-platform keys, chords and accessibility.

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

Power users love shortcuts: press / to focus the search box, Ctrl+S to save, g then i to go to the inbox, ? to list the commands. A shortcut system is a few lines of code when you start and a source of bugs when you ship it: it fires while the user types in a form field, it clashes with the browser's own shortcuts and with screen reader commands, it assumes a Mac or Windows keyboard, it ignores non-English layouts and it leaves no way to discover or turn off the keys. This guide shows how to make keyboard shortcuts in JavaScript: listening for keydown, reading event.key versus event.code, modifier keys, a small registry with a clean parser, ignoring typing contexts, cross-platform handling of Ctrl and Cmd, sequences such as g then i, preventing default behavior responsibly, key repeat, discoverability and accessibility rules, and testing. The events are documented on MDN and work in all browsers.

Listen for keydown

Attach a listener to the document, so shortcuts work wherever focus is, and read which key was pressed from the event.

basic.jsJavaScript
document.addEventListener("keydown", (event) => {
  console.log(event.key, event.code, event.ctrlKey, event.metaKey, event.shiftKey, event.altKey);
});
Text
s KeyS true false false false

Use keydown rather than keypress, which is deprecated and does not fire for many keys, and rather than keyup, unless the action should happen on release. The pressed key is described two ways. event.key is the character or key name that the layout produces: "s", "S" with Shift, "Enter", "Escape", "ArrowDown". event.code is the physical key position, such as "KeyS", "Digit1" or "Space", independent of layout.

key or code

The choice matters for non-US keyboards. A shortcut that is mnemonic, such as Ctrl+S for save, should use event.key, since people look for the letter on their keycaps, and on a French AZERTY keyboard the key labeled S is in a different physical place. A shortcut that is positional, such as the WASD keys for movement in a game or the keys under the left hand, should use event.code, so it keeps its place on any layout. Mixing them is a common source of bugs: event.key === "z" is true for the unshifted letter but "Z" appears with Caps Lock or Shift, so normalize with toLowerCase().

normalize.jsJavaScript
function keyName(event) {
  return event.key.length === 1 ? event.key.toLowerCase() : event.key;
}

document.addEventListener("keydown", (event) => {
  if (keyName(event) === "k" && (event.metaKey || event.ctrlKey)) {
    console.log("open command palette");
  }
});
Text
open command palette

A shortcut registry

Rather than a pile of if statements, register shortcuts as strings such as ctrl+k or shift+/, parse them once and look them up on each key press. A map keeps the code short and lets you list the shortcuts later.

registry.jsJavaScript
const shortcuts = new Map();

function parse(combo) {
  const parts = combo.toLowerCase().split("+");
  const key = parts.pop();
  return {
    key,
    ctrl: parts.includes("ctrl"),
    meta: parts.includes("meta") || parts.includes("cmd"),
    alt: parts.includes("alt"),
    shift: parts.includes("shift"),
  };
}

function register(combo, handler, description = "") {
  shortcuts.set(combo, { combo: parse(combo), handler, description });
  return () => shortcuts.delete(combo);
}

function matches(spec, event) {
  const key = event.key.length === 1 ? event.key.toLowerCase() : event.key.toLowerCase();
  return (
    key === spec.key &&
    event.ctrlKey === spec.ctrl &&
    event.metaKey === spec.meta &&
    event.altKey === spec.alt &&
    event.shiftKey === spec.shift
  );
}

document.addEventListener("keydown", (event) => {
  for (const { combo, handler } of shortcuts.values()) {
    if (matches(combo, event)) {
      event.preventDefault();
      handler(event);
      return;
    }
  }
});

register("ctrl+s", () => console.log("save"), "Save the document");
register("escape", () => console.log("close"), "Close the panel");
Text
save
close

Each registration returns a function that removes it, so a component can clean up. Requiring the modifiers to match exactly means ctrl+s does not fire for ctrl+shift+s, which is usually what you want. For a shortcut that is a printable character with Shift, such as ?, which needs Shift on a US keyboard, do not require shift in the spec, because event.key already reflects it; registering "?" with no modifiers works, so relax the shift check for symbol keys.

Ignore typing contexts

A single-letter shortcut such as / or j must not fire while the user types in a text field, or they cannot enter those letters. Check where the event happened and skip editable targets, unless the shortcut uses a modifier that cannot be part of typing.

guard.jsJavaScript
function isTypingTarget(target) {
  if (!(target instanceof HTMLElement)) return false;
  if (target.isContentEditable) return true;
  const tag = target.tagName;
  if (tag === "TEXTAREA" || tag === "SELECT") return true;
  if (tag === "INPUT") {
    const type = target.type;
    return !["checkbox", "radio", "button", "submit", "reset", "range", "color", "file"].includes(type);
  }
  return false;
}

document.addEventListener("keydown", (event) => {
  const hasModifier = event.ctrlKey || event.metaKey || event.altKey;
  if (!hasModifier && isTypingTarget(event.target)) return;
  // handle shortcuts here
});
Text
(typing "j" in a search box no longer triggers the next item shortcut)

Also ignore events during IME composition, where event.isComposing is true or the key code is 229, as those keystrokes build characters in languages such as Japanese and Chinese. And skip events that another handler already consumed, with event.defaultPrevented.

Cross-platform modifiers

The main modifier is Ctrl on Windows and Linux, and Cmd, reported as metaKey, on macOS. Support both, so mod+s means whichever fits the platform.

mod.jsJavaScript
const isMac = /Mac|iPhone|iPad/.test(navigator.platform) || navigator.userAgentData?.platform === "macOS";

function modPressed(event) {
  return isMac ? event.metaKey : event.ctrlKey;
}

function displayCombo(combo) {
  return combo
    .replace("mod", isMac ? "⌘" : "Ctrl")
    .replace("shift", isMac ? "⇧" : "Shift")
    .replace("alt", isMac ? "⌥" : "Alt")
    .replace(/\+/g, isMac ? "" : "+");
}

console.log(displayCombo("mod+shift+k"));
Text
⌘⇧k

Show the right label in the interface, for example in a tooltip, and write mod+ in your registry. Detecting the platform is one of the few places where the user agent is acceptable, because the question really is about the operating system's conventions.

Sequences and chords

Some tools use sequences: press g, then i within a second to go to the inbox. Track the recent keys with a buffer and a timeout.

sequence.jsJavaScript
let buffer = [];
let timer;

const sequences = {
  "g i": () => console.log("go to inbox"),
  "g s": () => console.log("go to starred"),
};

document.addEventListener("keydown", (event) => {
  if (isTypingTarget(event.target) || event.ctrlKey || event.metaKey || event.altKey) return;

  buffer.push(event.key.toLowerCase());
  clearTimeout(timer);
  timer = setTimeout(() => (buffer = []), 1000);

  const handler = sequences[buffer.join(" ")];
  if (handler) {
    event.preventDefault();
    handler();
    buffer = [];
  }
});
Text
go to inbox

After a handled sequence the buffer is cleared, and after one second without a key it resets. If one sequence is a prefix of another, such as g and g i, decide how to resolve the ambiguity, typically by not allowing a prefix to be a shortcut itself.

Prevent default carefully

Calling event.preventDefault() stops the browser's own action, which you need for Ctrl+S, which would otherwise open a save dialog. But overriding browser shortcuts hurts users: do not capture Ctrl+F, Ctrl+W, Ctrl+T, Ctrl+L, F5, Ctrl+R or text editing keys like Ctrl+C, which are not yours to take. Some shortcuts cannot be overridden at all. Call preventDefault() only for keys you actually handle, and never for Tab or Escape in a way that breaks focus movement and dismissal. Avoid single-key shortcuts that clash with assistive technology: screen readers use many bare letters in browse mode, and the WCAG success criterion on character key shortcuts says that single-character shortcuts must be able to be turned off, remapped or active only on focus.

Key repeat

Holding a key sends repeated keydown events, with event.repeat set to true after the first. For actions that must happen once, such as toggling a panel, ignore repeats, and for actions where holding makes sense, such as moving a selection, allow them.

repeat.jsJavaScript
document.addEventListener("keydown", (event) => {
  if (event.repeat) return;
  if (event.key === "p") togglePanel();
});
Text
(holding p toggles the panel once instead of flickering it)

Make them discoverable and optional

Hidden shortcuts help nobody. Show them next to the actions in menus and tooltips, and offer a help dialog on ? that lists every registered shortcut, built from the registry's descriptions. Provide a setting to disable single-key shortcuts and, if the application is large, to customize them. Document each in the user guide. Shortcuts should be an addition to, not the only way to reach, an action, since many users do not use keyboards that way, and touch devices have none.

help.jsJavaScript
function listShortcuts() {
  return [...shortcuts.values()].map(({ combo, description }) => `${displayCombo(combo)}: ${description}`);
}

register("?", () => console.log(listShortcuts().join("\n")), "Show keyboard shortcuts");
Text
Ctrl+s: Save the document
escape: Close the panel
?: Show keyboard shortcuts

Accessibility and special cases

Respect built-in widget keys: arrow keys in a menu, Space on a button, Enter on a link. A global shortcut must not run when a widget needs the key, so give components the first chance by calling event.stopPropagation() in their handlers, or check event.defaultPrevented. Use the aria-keyshortcuts attribute on the element an action belongs to, so that assistive technology can announce the shortcut, as in aria-keyshortcuts="Control+S". Keep focus indicators visible when shortcuts move focus, and do not trap keyboard focus. Test with screen readers, since some intercept keys before the page receives them.

Test it

In unit tests, dispatch synthetic events: document.dispatchEvent(new KeyboardEvent("keydown", { key: "s", ctrlKey: true })), and assert that the handler ran and defaultPrevented is true. Test inside an <input> to prove the guard works, with modifiers and without, with Caps Lock, on a layout where the character is in a different place and with an IME. Try the real shortcuts in Safari, Firefox and Chromium-based browsers, on macOS and Windows, because the browser's own keys differ.

test.jsJavaScript
const event = new KeyboardEvent("keydown", { key: "s", ctrlKey: true, cancelable: true });
document.dispatchEvent(event);
console.log(event.defaultPrevented);
Text
true
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.