Skip to curriculum
Jump to the editor

17.12. Keyboard shortcuts with modifiers

Medium
Topics
25–40 min

Editors, mail clients and dashboards all have keyboard shortcuts: Ctrl+S to save, Cmd+K to search on a Mac (Ctrl+K elsewhere), ? to list the shortcuts, j and k to move between items. Getting them right takes more than comparing event.key: modifiers must match exactly, a single-letter shortcut must not fire while someone types in a field, held keys repeat, and some keyboards change the character a modifier produces.

Write createShortcuts(target, options) in shortcuts.js.

Signature

JAVASCRIPT
function createShortcuts(target, options) // returns { add, destroy }

const keys = createShortcuts(document, { mac: false });
const remove = keys.add("ctrl+shift+p", (event) => openPalette(), { repeat: false });
remove();        // removes that shortcut
keys.destroy();  // removes every shortcut and the listener
  • options.mac: whether mod means meta (true) or ctrl (false). When it is missing, guess from navigator.platform.
  • A combo is zero or more modifiers (ctrl, alt, shift, meta, mod) and one key, joined by +, in any case and any order. The key is an event.key value (s, escape, arrowdown, ?), or space for " " and plus for "+".
  • handler receives the keydown event.

Requirements

  1. createShortcuts adds one keydown listener to target, which hears keys pressed anywhere inside it. Other events (such as keyup) are ignored.
  2. A press matches a combo when ctrlKey, altKey, shiftKey and metaKey are exactly the combo's modifiers, and the key matches.
  3. Keys are compared without case, so shift+p matches event.key "P". Symbols need the modifiers that produce them: ? is shift+?.
  4. When event.key does not match a letter or digit, event.code is checked: KeyS for s, Digit1 for 1. (On a Mac, Option+S types ß, and Shift+1 types !.)
  5. mod is meta when mac is true, ctrl otherwise.
  6. A match calls event.preventDefault() and then the handler. Keys that match nothing are left alone.
  7. While the event's target is an input, textarea, select or editable content (isContentEditable), combos without ctrl, alt or meta are ignored (shift alone does not count).
  8. Held keys (event.repeat) are ignored unless the shortcut was added with { repeat: true }. Keys pressed during text composition (event.isComposing) are ignored.
  9. Every handler whose combo matches runs, in the order added. A shortcut added by a handler runs from the next press, not during the current one. A shortcut removed by a handler stops at once: if it has not run yet in the current press, it does not run.
  10. add returns a function that removes that one shortcut (calling it twice is harmless). destroy removes the listener and all shortcuts. Two sets of shortcuts are independent.
  11. An invalid combo throws a SyntaxError: an empty combo, no key (ctrl, ctrl+shift, shift+mod), an unknown modifier (cmd+k, a+b), or a modifier used twice.

Examples

JAVASCRIPT
const keys = createShortcuts(document, { mac: true });

keys.add("mod+k", openSearch);     // Cmd+K
keys.add("shift+?", showHelp);     // Shift+/ on a US keyboard
keys.add("j", nextItem);           // not while typing in a field
keys.add("arrowdown", moveDown, { repeat: true });
JAVASCRIPT
// Ctrl+Shift+S does not run "ctrl+s"; Ctrl+S does, and the browser's Save dialog stays closed.
keys.add("ctrl+s", save);
JAVASCRIPT
keys.add("cmd+k", openSearch); // throws SyntaxError: use meta or mod

Environment

  • Plain JavaScript in a browser page; the tests call createShortcuts on elements they build and dispatch real KeyboardEvents with key, code and modifier flags.
  • Sequences (g then i), different layouts' symbol positions and remapping by users are out of scope.

Hints

  1. Parse each combo once, in add, into four booleans and a key. What is left to do on each keydown?
  2. How can a loop over the shortcuts ignore shortcuts that handlers add while it runs, but still skip one that a handler has just removed?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…