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 of keyCode or which with the number of a key that has a name. For example, event.keyCode === 13 becomes event.key === 'Enter'. For a key that writes a character, key depends on the layout and on Shift: keyCode 65 is both a and A. Only --fix-dangerously rewrites those.
Configure#
Off by default. To turn it on:
[lint.rules]
"unicorn/prefer-keyboard-event-key" = "error" # or "warn"Examples#
input.addEventListener("keydown", event => {
if (event.keyCodeUse .key instead of .keyCode === 13) {
submit();
}
});dialog.addEventListener("keyup", ({ whichUse .key instead of .which }) => {
if (which === 27) {
dialog.close();
}
});input.addEventListener("keydown", event => {
if (event.key === "Enter") {
submit();
}
});
dialog.addEventListener("keyup", ({ key }) => {
if (key === "Escape") {
dialog.close();
}
});