Keyboard Hotkey Map With Modifier Combinations

Turn keydown events into actions with a hotkey map; modifier keys join the combination and text inputs plus IME composition are skipped.

JavascriptForm Validation

Code

javascriptsnippet
30 lines
// Hotkey map: keydown combinations become actions; modifier keys are part
// of the combination so Ctrl+S never triggers the plain S handler
const hotkeys = {
  'mod+s': () => console.log('action: save'),
  'mod+shift+p': () => console.log('action: command palette'),
  '?': () => console.log('action: help overlay'),
};

document.addEventListener('keydown', (event) => {
  const tag = event.target?.tagName;
  if (tag === 'INPUT' || tag === 'TEXTAREA' || event.isComposing) return;

  const key = event.key.toLowerCase();
  const isLetter = key.length === 1 && key >= 'a' && key <= 'z';
  const combo = [];
  if (event.ctrlKey || event.metaKey) combo.push('mod');
  if (event.altKey) combo.push('alt');
  // shift is only a modifier for letters: on most layouts the '?' key
  // already carries the shift inside the key itself
  if (event.shiftKey && isLetter) combo.push('shift');
  combo.push(key);

  const handler = hotkeys[combo.join('+')];
  if (handler) {
    event.preventDefault();
    handler();
  }
});

console.log('registered hotkeys:', Object.keys(hotkeys).join(', '));

Inside the snippet

Top-level bindings hotkeys hold the demo state — nothing sits inside a function scope.

Watch out for

  • A browser is the runtime here: document are not available in Node.
  • The guard tag === 'INPUT' || tag === 'TEXTAREA' || event.isComposing short-circuits the flow with an early return when its condition holds.

Putting it to use

The file’s steps show up in the output as action: save, action: command palette, action: help overlay.

Core lines

const tag = event.target?.tagName;

Interactive Tools for This Topic

FAQ

Does Keyboard Hotkey Map With Modifier Combinations run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.