unicorn/prefer-keyboard-event-key

Require event.key instead of keyCode, charCode and which

fixable

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:

bunfig.toml
[lint.rules]
"unicorn/prefer-keyboard-event-key" = "error" # or "warn"

Examples#

example.js1 problem
input.addEventListener("keydown", event => {
  if (event.keyCode === 13) {
    submit();
  }
});
example.js1 problem
dialog.addEventListener("keyup", ({ which }) => {
  if (which === 27) {
    dialog.close();
  }
});
example.jsNo problems
input.addEventListener("keydown", event => {
  if (event.key === "Enter") {
    submit();
  }
});

dialog.addEventListener("keyup", ({ key }) => {
  if (key === "Escape") {
    dialog.close();
  }
});