How do I detect keypresses in JavaScript?
Here is a quick way to detect keypresses in JavaScript using the keydown
event via addEventListener
function:
This code snippet will log the name of every key pressed. You extract the name of the pressed key using e.key
.
Getting to know keyboard events
Keyboard events in JavaScript can be divided into three categories — keydown
, keyup
, and keypress
. Understanding their differences and usage is critical:
keydown
: Fires when a key is pressed, detects all keys inclusive of Shift, Alt, etc.keyup
: Executes when a key is released.keypress
: This is deprecated and should be avoided. It doesn't recognize non-character keys. Usekeydown
orkeyup
instead.
Opt for modern practices
For the best compatibility with modern browsers, go for event.key
and event.code
:
event.key
: Returns the unmodified character associated with the pressed key (e.g. "a", "A", "1", "Enter").event.code
: Precisely indicates the physical key location on your keyboard (e.g. "KeyA", "Digit1", "Enter"), irrespective of the language or modifier key status.
An example of how event.code
works:
Favor these over the outmoded keyCode
for readability and future compatibility.
The jQuery approach
If you're a jQuery user, it abstracts away many low-level details and eases up the syntax of binding keyboard events:
While beneficial for handling cross-browser compatibility, mastering JavaScript fundamentals remain imperative. Do remember that jQuery is an addition, and not a replacement for fundamental JavaScript.
Considering performance
Performant code matters! Keep your keypress event handlers as non-intensive as possible. If you're attaching numerous event listeners or executing complex tasks within the listeners, consider debouncing or profiling your code with performance-oriented tools like jsbench.me.
Effective code organization and best practices
Writing separate functions for key handlers
Good organization often leads to maintainable code. For different key handling, individual functions enhance clarity:
Exploring the beforeinput
event
In scenarios requiring input manipulation prior to screen display, don't hesitate to employ beforeinput
:
Embracing ES6 features
Arrow functions, a popular ES6 feature, make your event handlers more concise and readable:
Know your users' environment
Ensure the browsers you're targeting support the features you use. While event.key
and event.code
enjoy support from most modern browsers, cross-check against caniuse.com just to be sure.
Was this article helpful?