Frictionless hotkey handling for browsers
Frictionless hotkey handling for browsers
import { captureKeys } from "keez";
const saveCommand = captureKeys("CmdOrCtrl", "S");
const italicCommand = captureKeys("CmdOrCtrl", "I");
document.addEventListener("keydown", (event) => {
if (saveCommand(event)) {
/* Do something, e.g. call `fetch` */
} else if (italicCommand(event)) {
/* Do something else, e.g. format selected text */
}
});
CmdOrCtrl
modifier for interoperability between operating systemsevent.preventDefault()
when a match is found, suppressing handlers of the underlying browser (or even the system)Every browser with the Set
built-in is supported out of the box.
There are quite a few attributes to handle keystrokes with:
Layout-aware | Modifier-independent | Supports all events | Named non-printables | |
---|---|---|---|---|
key |
✓ | ✗ | ✓ | ✓ |
code |
✗ | ✓ | ✓ | ✓ |
keyCode / which (legacy) |
✓ | ✓ | ✓ | ✗ |
charCode (legacy) |
✓ | ✓ | ✗ | ✗ |
Despite being a legacy attribute, keyCode
is used in comparisons by default. It’s independent from modifiers, unlike the modern key
alternative.
However, when it comes to named key attribute values (e.g. Escape
or Backspace
), the key
property is used under the hood.