Linter · Rules
unicorn/prefer-keyboard-event-key
Require event.key instead of keyCode, charCode and which
keyCode, charCode and which are deprecated. They're numbers that you have to look up, and they differ between browsers and keyboard layouts. key is a string that names the key, like "Enter", "Escape" or "a".
The rule looks at the event parameter of a function written inside the addEventListener() call, both where a property is read and where it's destructured. A handler that's defined somewhere else and passed by name isn't checked. The event type isn't checked either, so event.which in a "mousedown" listener is reported too.
--fix rewrites a == or === comparison with a number. For example, event.keyCode === 13 becomes event.key === 'Enter'.
Configure
Off by default. To turn it on:
[lint.rules]
"unicorn/prefer-keyboard-event-key" = "error" # or "warn"
Examples
Reported:
input.addEventListener("keydown", event => {
if (event.keyCode === 13) {
submit();
}
});
dialog.addEventListener("keyup", ({ which }) => {
if (which === 27) {
dialog.close();
}
});
Not reported:
input.addEventListener("keydown", event => {
if (event.key === "Enter") {
submit();
}
});
dialog.addEventListener("keyup", ({ key }) => {
if (key === "Escape") {
dialog.close();
}
});