Skip to content

Websites

Content sites and docs need only a few shortcuts, but they should feel native: open search, show the shortcuts, close what is open. They also have to stay out of the way of people typing and of assistive technology.

import { createShortcutter } from 'shortcutter';
const shortcutter = createShortcutter();
const search = document.querySelector<HTMLInputElement>('#search')!;
shortcutter.listen('ControlOrMeta+K', () => search.focus(), {
preventDefault: true, // instead of the browser's own Ctrl+K (its search bar)
description: 'Search',
});
shortcutter.listen('Slash', () => search.focus(), {
preventDefault: true, // do not type "/" into the field
description: 'Search',
});

Both are ignored while the user types in a field, so a / inside the search box is just a slash.

Two conventions are common: ⌘ / Ctrl + / (Google Docs, Slack) and ? (Gmail, GitHub). Register both, describe them, then build the dialog from the registry:

shortcutter.listen('ControlOrMeta+Slash', openHelp, {
preventDefault: true,
description: 'Show keyboard shortcuts',
});
shortcutter.listen('Shift+Slash', openHelp, { description: 'Show keyboard shortcuts (?)' });
function openHelp() {
list.replaceChildren(
...shortcutter.shortcuts({ active: true }).map(({ keys, description }) => row(keys, description)),
);
dialog.showModal();
}
shortcutter.listen('Escape', () => dialog.close(), {
context: 'dialog',
ignoreInputs: false, // also from inside the dialog's search field
});
dialog.addEventListener('close', () => shortcutter.contexts.activate('default'));

GitHub-style G then H navigation comes from the optional sequences entry, so pages without it ship nothing extra:

import { createSequences } from 'shortcutter/sequences';
const sequences = createSequences(shortcutter);
sequences.listen('G H', () => location.assign('/'), { description: 'Go home' });
sequences.listen('G D', () => location.assign('/docs/'), { description: 'Go to the docs' });

WCAG 2.1 success criterion 2.1.4 (Character Key Shortcuts) asks that shortcuts made of a single character can be turned off or remapped, because speech-input users trigger them by accident. Contexts make the off switch one line:

// Single-key shortcuts live in their own context…
shortcutter.listen('Slash', focusSearch, { context: 'single-keys' });
shortcutter.listen('Shift+Slash', openHelp, { context: 'single-keys' });
// …that a setting can leave out.
const contexts = settings.singleKeyShortcuts ? ['default', 'single-keys'] : ['default'];
shortcutter.contexts.activate(...contexts);

Shortcuts with ⌘/Ctrl are not affected by this criterion.

Importing shortcutter on the server is safe: without a window, nothing is attached. In Astro, Next, Nuxt or SvelteKit, register shortcuts in client code, or use the framework adapters, which only register after mount.