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.
Code
// 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:
documentare not available in Node. - The guard
tag === 'INPUT' || tag === 'TEXTAREA' || event.isComposingshort-circuits the flow with an earlyreturnwhen 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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.