How to Use Keyboard Listeners in Vanilla JavaScript

William Le

In this article, you’ll learn about how to listen to your user’s keyboards to create new and fascinating features for your web apps!

Listening to your user’s keyboard is a really handy tool to have. We might not think of it this way, but the browser is constantly listening to the keyboard! When you place the text cursor into an <input> box, it’s listening to the keyboard. When you press the key, your webpage will scroll down.

As a web developer, you’re given these same tools too! And it’s not difficult either…

// Listening for keyboard event
document.addEventListener('keydown', fn);

// Listening for scrolling event
document.addEventListener('scroll', fn);

// Listening when browser window is resized
document.addEventListener('resize', fn);

Listening to the keyboard is exactly like listening to the scroll and resize browser events. In addition to the keydown event, you can also listen for the keyup event (though it’s not quite as popular).

// Triggers when key is depressed
document.addEventListener('keydown', fn);

// Triggers when key is released
document.addEventListener('keyup', fn);

Basic Usage

Let’s look at a short example where we listen for the “d” and “l” keys to be pressed. Pressing these keys will change the website from dark/light mode:

document.addEventListener('keydown', function (event) {
  if (event.key === 'd') {
    document.body.style = "color: white; background-color: #111111";
  }
  if (event.key === 'l') {
    document.body.style = '';
  }
});

In the callback function, the event argument is a KeyboardEvent that possesses several useful properties/methods. The important one we’re using is event.key which gives you a plaintext output of the key that’s pressed 👉⌨️

This article is best viewed on a desktop/laptop computer with a physical keyboard to fully experience the demos

That’s it! It’s pretty straightforward to listen to the keyboard. 🙌

Listening for Modifier Keys

There is an added utility for listening for modifier keys. They’re useful for invoking combo keystrokes (like Ctrl + s to “save”).

Luckily, you can do it pretty easily with event.ctrlKey!

document.addEventListener('keydown', function (event) {
  // CTRL + S combo
  if (event.ctrlKey && event.key === 'd') {
    document.body.style = "color: white; background-color: #111111";
  }
  // CTRL + L combo 
  if (event.ctrlKey && event.key === 'l') {
    document.body.style = '';
  }
});

For those that are on Windows/Linux OS, you might have encountered a small problem… Pressing Ctrl + d prompted you to bookmark the URL! This is happening because your browser triggers your own custom keyboard events AND with the browser’s default events.

This can be easily fixed using event.preventDefault:

document.addEventListener('keydown', function (event) {
  event.preventDefault();
  // CTRL + S combo
  if (event.ctrlKey && event.key === 'd') {
    document.body.style = "color: white; background-color: #111111";
  }
  // CTRL + L combo 
  if (event.ctrlKey && event.key === 'l') {
    document.body.style = '';
  }
});

Want to listen for the Alt or Shift keys instead? There’s properties for those too!

  • event.ctrlKey: the Ctrl key
  • event.altKey: the Alt key
  • event.metaKey: the “meta” key differs based on the OS. For example, on Mac OSX it’s the ⌘ Command key
  • event.shiftkey: the Shift key

Until recently the conventional way to listen to the keyboard was via event.keyCode instead of event.key. Many forums/blogs like StackOverflow still heavily feature keyCode however beware... It is deprecated!

Conclusion

Listening to the keyboard allows you to build lots of interesting features! You can create a web-based video game, or add keyboard shortcuts to your app so users feel more productive. Hopefully this has whet your appetite, and given you a solid foundation for creating keyboard listeners!

Visit MDN for full documentation on KeyboardEvent

  Tweet It

🕵 Search Results

🔎 Searching...