DEV Community

Michael Burrows
Michael Burrows

Posted on • Originally published at w3collective.com

2

Creating keyboard shortcuts for web apps with JavaScript

In this tutorial we’ll be creating keyboard shortcuts that can be used in web apps. These are particularly handy when you want to give users the ability to save or copy data, navigate, or control playback of media all via the keyboard.

First thing we’ll do is create an object with the keys we want to use as shortcuts:

let keyDown = {
  'c': false,
  'p': false,
  's': false,
  'Meta': false,
  'Control': false
};
Enter fullscreen mode Exit fullscreen mode

The shortcuts we are creating will be triggered using the control or command keys in conjunction with another alphabetical key. Control here represents the control key whilst Meta represents the command key on macOS devices.

Next we’ll setup a keydown event listener that calls a handleKeydown function:

document.addEventListener("keydown", handleKeydown);
function handleKeydown(e) {
  e.preventDefault();
  keyDown[e.key] = true;
  if (keyDown["c"] && (keyDown["Control"] || keyDown["Meta"])) {
    console.log("Shortcut Activated");
  }
}
Enter fullscreen mode Exit fullscreen mode

This function sets the value of the key in the keyDown object to true. In this example we are checking if the “c” key has been pressed along with either the “Control” or “Meta” keys. As we’ve built it this way we could check for any number of key combinations pressed simultaneously.

To finish we just need to add a keyup event listener that resets the key value to false:

document.addEventListener("keyup", handleKeyup);
function handleKeyup(e) {
  keyDown[e.key] = false;
}
Enter fullscreen mode Exit fullscreen mode

That’s all for this tutorial, you should now have a good understanding of how to create keyboard shortcuts using JavaScript. If you enjoyed this tutorial we also have a number of other JavaScript tutorials for both new and experienced developers.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay