# 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'`.

{/* Generated by src/codegen/lint-rule-docs.ts. Do not edit this section. */}

## Configure

Off by default. To turn it on:

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

{/* End of the generated section. */}

## Examples

Reported:

{/* bad */}
```js
input.addEventListener("keydown", event => {
  if (event.keyCode === 13) {
    submit();
  }
});
```

{/* bad */}
```js
dialog.addEventListener("keyup", ({ which }) => {
  if (which === 27) {
    dialog.close();
  }
});
```

Not reported:

{/* good */}
```js
input.addEventListener("keydown", event => {
  if (event.key === "Enter") {
    submit();
  }
});

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