Keyboard Event Viewer · Tutorial

How to add a keyboard shortcut to a web app

7 min readintermediateUpdated

You want Ctrl + K (Cmd + K on a Mac) to open search in your web app. This tutorial uses the Keyboard Event Viewer to see what the browser reports, copies a condition that works on every keyboard layout, and wires it up so it doesn’t interfere with typing.

What you need

Steps

  1. Press the shortcut in the viewer

    Click the big box and press Ctrl + K. The viewer shows event.key as "k", event.code as KeyK and Ctrl as the modifier. On a Mac, press Cmd + K and you’ll see Meta instead.

  2. Copy the condition

    Copy the JavaScript under Check for this key in JavaScript. It checks event.code === 'KeyK' rather than the letter, so the shortcut stays on the same physical key with French, German or Cyrillic layouts.

  3. Support both Ctrl and Cmd

    Combine the two conditions so Windows and Linux users use Ctrl and Mac users use Cmd.

    document.addEventListener('keydown', (event) => {
      if (event.code === 'KeyK' && (event.ctrlKey || event.metaKey)) {
        event.preventDefault();
        openSearch();
      }
    });
  4. Don’t steal keys while typing

    Single-key shortcuts like "/" are handy, but should be ignored while the user types in a field. Check the focused element before acting.

    const typing = event.target.closest('input, textarea, [contenteditable="true"]');
    if (event.key === '/' && !typing) { /* … */ }
  5. Avoid reserved shortcuts

    Try your shortcut in the viewer; if it shows a warning, the browser keeps it for itself. Ctrl + W, Ctrl + T and Ctrl + N can’t be used reliably.

  6. Tell people about it

    Show the shortcut in a tooltip or menu, and offer the same action with a button, because not everyone uses a keyboard.

Try it yourself

Opens the Keyboard Event Viewer.

Try it now

Common mistakes

Checking event.key for letters with Ctrl
On some layouts, the K position produces a different letter. Use event.code for shortcuts and event.key for typed text.
Using keyCode
keyCode is deprecated and differs between layouts and browsers. Avoid it in new code.
Forgetting preventDefault
Without it, the browser may also run its own action for the shortcut, such as focusing the address bar.

Next steps

Go back to the Keyboard Event Viewer, or keep going with one of these:

FAQ

Does it work with screen readers?

Screen readers use many keys themselves. Shortcuts with Ctrl or Cmd usually pass through, but always offer a visible button too.

How do I support a shortcut with Shift?

Add event.shiftKey to the condition; the viewer includes it when you hold Shift.