Explain Codes LogoExplain Codes Logo

How do I detect keypresses in JavaScript?

javascript
event-handling
keyboard-events
javascript-fundamentals
Anton ShumikhinbyAnton Shumikhin·Oct 21, 2024
TLDR

Here is a quick way to detect keypresses in JavaScript using the keydown event via addEventListener function:

document.addEventListener('keydown', (e) => console.log(`You pressed: ${e.key}`));

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. Use keydown or keyup 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:

document.addEventListener('keydown', function(event) { if (event.code === 'KeyA') { console.log('You found the A key. Achievement unlocked!'); } });

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:

$(document).keydown(function(event) { console.log(`Key pressed with jQuery: ${event.key}`); });

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:

const handleArrowLeft = (event) => { if (event.key === 'ArrowLeft') { // make an U-turn ↩️ } }; // Easier visual parsing document.addEventListener('keydown', handleArrowLeft);

Exploring the beforeinput event

In scenarios requiring input manipulation prior to screen display, don't hesitate to employ beforeinput:

document.addEventListener('beforeinput', (event) => { console.log(`Input before hitting the screen: ${event.data}`); });

Embracing ES6 features

Arrow functions, a popular ES6 feature, make your event handlers more concise and readable:

document.addEventListener('keydown', (event) => { // This saves a couple of bytes, and every byte counts! 💾 });

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.