Keyboard Events TL;DR

Feb 18, 2020 Programming, JavaScript, Web API,
Illustration: Raymond Sohn

Illustration: Raymond Sohn

TL;DR


  • Use the key attribute or the code attribute instead of charCode, keyCode, or which.
  • Do not use the keypress event.
  • To detect common modifier keys use the boolean attributes altKey, ctrlKey, metaKey, and shiftKey. To detect any other modifier keys use the getModifierState function.

Web standards are always changing and it should come as no surprise that even the modest Keyboard Event API has received a few updates. The good news is that it’s been improved for the betterment of all developers.

Browser support for keyboards has traditionally relied on three ad-hoc attributes, keyCode, charCode, and UIEvent's which.

The biggest source of confusion for me has always been trying to figure out which of the 3 ways to get the key code was the correct way. For God’s sake, I just want to know which key is being pressed!

I’m glad to report back that the W3C has deprecated all 3 of these attributes [1] in the DOM Level 3 specification and they now recommended using either the key attribute [2] or the code attribute [3] .

The key attribute returns a human-readable string for both printable and non-printable control characters. And the code attribute returns a string representing the physical position of the key on your particular keyboard.

Warning! The keypress event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type.

Another surprising change in the DOM Level 3 specification is that the keypress event has been deprecated. This is a great design choice because:

  • there is a confusing overlap in functionality between the keypress event and the keydown event. The keypress event behaves almost exactly like the keydown event except that the former does not receive control characters.
  • having fewer events to choose from reduces the surface area of the API and thus places less cognitive load on the developer.

Finally, it’s now possible to detect modifier keys besides Alt, Control, Meta and Shift. With the getModifierState function [4] you can detect modifier keys such as CapsLock, NumLock and other OS specific modifiers like Win for Internet Explorer.

Thanks to Michael Geraci and MarĂ­n Alcaraz for editing.
If you liked this post, you might also like JavaScript Arrow Function Gotchas or 7 Ways to Loop in JavaScript.
2019-2020, Raymond Sohn.