Skip to content
All articles

A Page-Wide Keyboard Listener That Never Gets in the Way

5 min read

The hero of this site is a 3D keyboard. It seemed obvious that typing on your real keyboard should press the matching key on it, so I added a keydown listener on the window. That is a few lines. Making sure it could never get in anyone's way was the actual work, because a page-wide keyboard listener sits in front of every keystroke a visitor makes — including the ones they type into the contact form further down.

Five guards, each for a specific way it could have gone wrong.

1. Never call preventDefault

The listener only observes. It never calls event.preventDefault(), so nothing it does can stop a keystroke reaching where it was going: a form field, the browser's own shortcuts, the space bar scrolling the page.

This is the guard that makes the others safe to get slightly wrong. If a listener can swallow keys, every mistake in it breaks someone's typing. If it cannot, the worst case is a decorative key moving when it should not have.

2. Stand down while someone is typing

const isTypingTarget = (node) => {
  if (!(node instanceof HTMLElement)) return false
  if (node.isContentEditable) return true
  return ['INPUT', 'TEXTAREA', 'SELECT'].includes(node.tagName)
}

A keydown event's target is the focused element. If that is a field, the visitor is writing something, and a decorative reaction to their message is the last thing they need. Checking isContentEditable as well covers rich-text editors, which are not inputs at all.

3. Ignore modifier combinations

Ctrl+R is a reload, Cmd+K is often a search box, Alt combinations do different things on every platform. None of those is someone typing a letter, so the listener returns early when ctrlKey, metaKey or altKey is set.

4. Ignore held keys

Holding a key fires keydown repeatedly at the operating system's repeat rate. Without a check on event.repeat, holding A machine-guns the A key on the model, which looks broken rather than playful.

5. Only single characters

event.key is a printable character for letter keys and a name for everything else: Tab, Escape, ArrowLeft, F5. Checking event.key.length === 1 keeps the listener to the keys it can actually map, and leaves navigation keys entirely alone.

One more, for cost rather than correctness: the listener does nothing while the canvas is off screen or the tab is hidden. There is no point animating a key nobody can see.

Testing it

Every guard is testable from the browser console by dispatching events and checking defaultPrevented:

const ev = new KeyboardEvent('keydown', { key: 'a', bubbles: true, cancelable: true })
document.body.dispatchEvent(ev)
ev.defaultPrevented // must be false

I ran that for the whole alphabet, digits, punctuation, Tab, Escape, F5 and arrow keys, each with and without repeat: 96 events, none prevented. Then focused a real form field, dispatched keys into it, and confirmed it accepted the text and kept focus.

The easter egg rides on the same handler

The accent keys on the model spell a name. Type it and they light up in order. That is a short buffer — the last few characters typed, trimmed to the length of the secret word — checked in the same handler, so it inherits all five guards for free. It cannot fire from the contact form, cannot be triggered by a held key, and cannot interfere with anything.

The general shape is worth keeping for any page-wide listener: make it unable to cause harm first, then decide what it should do. A decorative feature that occasionally steals a keystroke is not decorative any more.