
shortcutter is a dependency-free JavaScript library for adding keyboard shortcuts to browser apps. It lets you activate bindings for a dialog, editor, or other page state.
Features
- Key combinations support Ctrl, Command, Shift, Alt, and platform-aware modifiers.
- Wildcard patterns match groups of arrow keys, letters, digits, and function keys.
- Key phases distinguish the initial press, key repetition, and release.
- Optional key sequences support commands such as
G H. - Registrations include descriptions for keyboard shortcut help lists.
- Shortcuts are ignored during text entry and IME composition by default.
- React, Vue, Svelte, and Solid adapters.
How To Use shortcutter
Basic Usage: Open a Command Dialog
This browser example opens a command dialog with Ctrl+K on Windows/Linux or Command+K on macOS. Escape closes the dialog even when its search field has focus. Dialog-specific shortcuts take priority while it is open.
<button type="button" id="open-commands">Open commands</button>
<dialog id="commands" aria-labelledby="commands-title">
<h2 id="commands-title">Commands</h2>
<label for="command-search">Search commands</label>
<input id="command-search" type="search">
<h3>Keyboard shortcuts</h3>
<ul id="shortcut-help"></ul>
<form method="dialog">
<button type="submit">Close</button>
</form>
</dialog>
<p id="keyboard-hints" hidden>Press Ctrl/Command+K to open commands.</p>
<script src="https://unpkg.com/[email protected]/dist/index.iife.js"></script>
<script>
const commands = document.querySelector('#commands');
const shortcutter = Shortcutter.createShortcutter();
let previousContexts = shortcutter.contexts.active();
function openCommands() {
if (commands.open) return;
previousContexts = shortcutter.contexts.active();
commands.showModal();
shortcutter.contexts.activate('dialog', ...previousContexts);
}
document.querySelector('#open-commands').addEventListener('click', openCommands);
shortcutter.listen('ControlOrMeta+K', openCommands, {
preventDefault: true,
description: 'Open commands'
});
shortcutter.listen('Escape', () => commands.close(), {
context: 'dialog',
ignoreInputs: false,
preventDefault: true,
description: 'Close commands'
});
commands.addEventListener('close', () => {
shortcutter.contexts.activate(...previousContexts);
});
</script>
Install with npm
Use the core package in place of the browser script. The dialog markup above works with this handler.
npm install shortcutter
import { createShortcutter } from 'shortcutter';
const shortcuts = createShortcutter();
shortcuts.listen('ControlOrMeta+K', () => {
const dialog = document.querySelector('#commands');
if (dialog && !dialog.open) dialog.showModal();
}, { preventDefault: true });
Match Keys with Wildcards and Phases
Shortcut names follow physical key positions from KeyboardEvent.code, which matters for non-US keyboard layouts.
Patterns such as Shift+Arrow* match a family of keys; an exact binding takes priority over a wildcard in the same context.
Use the down and up phases to react when a key is pressed or released, including when focus leaves the page.
shortcutter.listen('Shift+Arrow*', (_event, { shortcut }) => {
console.log('Selection shortcut:', shortcut);
});
shortcutter.listen('Alt', (_event, { phase }) => {
document.querySelector('#keyboard-hints').hidden = phase !== 'down';
}, { phases: ['down', 'up'] });
Register Multi-Step Keyboard Sequences
Load the optional sequences build after the core script. G H runs when those keys are pressed in order within the timeout.
Keep letter-only commands in a context that a user setting can turn off or remap.
<script src="https://unpkg.com/[email protected]/dist/sequences.iife.js"></script> <script> const sequences = ShortcutterSequences.createSequences(shortcutter, { timeout: 1000 }); sequences.listen('G H', () => { window.location.assign('/'); }, { context: 'navigation', description: 'Go to the homepage' }); shortcutter.contexts.activate('navigation', 'default'); // To disable letter-only navigation, activate just 'default'. </script>
In an npm project, import the sequence module alongside your existing shortcuts instance:
import { createSequences } from 'shortcutter/sequences';
const sequences = createSequences(shortcuts, { timeout: 1000 });
Generate a Shortcut Help List
Populate the #shortcut-help list in the browser example from registered shortcuts.
Include
sequences.sequences()when your help screen also needs multi-step commands.
const helpList = document.querySelector('#shortcut-help');
const items = shortcutter.shortcuts()
.filter(({ description }) => description)
.map(({ keys, description }) => {
const item = document.createElement('li');
item.textContent = `${keys.join(' + ')}: ${description}`;
return item;
});
helpList.replaceChildren(...items);
Configuration and API Reference
`createShortcutter(options?)`
The initializer returns a shortcut manager.
| Option | Description |
|---|---|
target | Event target for keyboard listeners. Defaults to window in a browser. No listeners attach when no target exists during server rendering. |
signal | Optional AbortSignal. Aborting it stops the manager, like destroy(). Default: none. |
defaultContext | Initially active context and default registration context. Default: 'default'. |
ignoreInputs | Skip shortcuts in inputs, textareas, selects, contenteditable elements, and during IME composition. Default: true. |
preventDefault | Call event.preventDefault() when a handler runs. Default: false. |
mac | Override macOS detection used by ControlOrMeta. Default: platform detection. |
Shortcut Registration Options and Handler Details
Register keys with listen(shortcut, handler, options?). Key names are case-insensitive, and modifiers can appear in any order.
Use + between keys: Control (Ctrl), Alt (Option), Shift, Meta (Cmd or Command), and ControlOrMeta are supported modifiers.
listen() option | Description |
|---|---|
description | Optional text for help displays. |
context | Registration context. Default: the instance’s defaultContext. |
phases | 'down', 'press', 'up', or an array of these values. Default: 'down'. |
ignoreInputs | Overrides the instance input guard for this shortcut. |
preventDefault | Overrides the instance’s default-prevention setting. |
The handler receives (event, detail). The detail object contains these fields:
| Field | Description |
|---|---|
phase | The matching 'down', 'press', or 'up' phase. |
shortcut | Canonical keys actually held, such as 'arrowup+shift'. |
pattern | Canonical registered combination, including any wildcard. |
context | Context responsible for the match. |
description | Registration description, when present. |
event is normally a KeyboardEvent; an 'up' callback caused by losing focus or leaving the page receives the relevant browser event. Supported wildcard patterns include Key*, Digit*, F*, Arrow*, Numpad*, and *. Each * matches one non-modifier key.
Shortcut Manager Methods
| Method | Description |
|---|---|
listen(shortcut, handler, options?) | Register a shortcut and return a cleanup function. A duplicate combination for the same phase and context throws. |
unlisten(shortcut, { context?, phases? }) | Remove matching registrations. Defaults to the default context and 'down' phase; missing bindings are ignored. |
shortcuts({ active?, context? }) | Return registered shortcuts in registration order. Each entry includes shortcut, keys, context, phases, description (when set), and active. |
contexts.activate(...names) | Replace active contexts with the supplied names, in priority order. An empty call deactivates all contexts. |
contexts.active() | Return the active context names. |
contexts.isActive(name) | Check whether a context is active. |
resolve(shortcut) | Return canonical keys for the current platform, modifiers first. Invalid combinations throw. |
isPressed(shortcut) | Check whether all keys in the combination are held, including wildcard matches. |
pressed() | Return the currently held canonical keys. |
subscribe(listener) | Call listener(pressed, event) when held keys change. Returns an unsubscribe function. |
observe(listener) | Call listener(event, { phase, shortcut }) for all key phases, including unmatched and input-field activity. Ignores contexts and the input guard; returns an unsubscribe function. |
destroy() | Remove the instance’s event listeners and stop shortcut handling. |
Sequence API
createSequences(shortcutter, { timeout? }) accepts an existing manager and creates a sequence manager. The maximum interval between steps defaults to 1000 milliseconds. Sequences require at least two steps and can contain modifiers or wildcards.
sequences.listen() option | Description |
|---|---|
description | Optional description for a help screen. |
context | Context where the sequence is active. Default: 'default'. |
ignoreInputs | Skip sequences while typing in editable controls. Default: true. |
preventDefault | Prevent the default action of the keydown event completing the sequence. Default: false. |
| Method | Description |
|---|---|
sequences.listen(sequence, handler, options?) | Register a sequence and return its cleanup function. Duplicate steps in a context throw. The handler receives (event, { sequence, context, description? }). |
sequences.sequences({ active?, context? }) | Return registrations with sequence, resolved steps, context, optional description, and active. Filter by active status or context. |
sequences.destroy() | Stop sequence observation and remove registered sequences. |
Framework Adapters
Install shortcutter alongside your framework adapter. The helpers accept shortcut or sequence options plus enabled (default true) and remove registrations on unmount.
Vue supports refs and getters, Solid supports accessors, and Svelte offers element attachments. Each adapter supports a shared manager or one provided through context.
| Package | Public helpers and requirement |
|---|---|
@shortcutter/react | useShortcut(), useSequence(), useShortcutter(), ShortcutterProvider with shortcutter and children props. React 18+. |
@shortcutter/vue | useShortcut(), useSequence(), useShortcutter(), provideShortcutter(), shortcutterKey. Vue 3.3+. |
@shortcutter/svelte | useShortcut(), useSequence(), shortcut() and sequence() attachments, getShortcutter(), setShortcutter(). Attachments also accept a shortcutter instance. Svelte 5.29+. |
@shortcutter/solid | createShortcut(), createSequence(), useShortcutter(), ShortcutterContext.Provider with a manager passed as value. Solid 1.8+. |
For React, install the adapter and register shortcuts inside a component:
npm install shortcutter @shortcutter/react
import { useShortcut } from '@shortcutter/react';
function CommandShortcut({ onOpen }) {
useShortcut('ControlOrMeta+K', onOpen, { preventDefault: true });
return null;
}
Alternatives and Related Resources
- Hotkeys.js: JavaScript Keyboard Shortcut Library
- Tiny Key Binding JavaScript Library – Tinykeys.js
- Tiny & Robust Keyboard Shortcut Solution For JavaScript – Mousetrap







