#AD Top Online Web Development & Programming Courses | Udemy

Creating keyboard shortcuts for web apps with JavaScript

Last modified March 8th 2022 | #js | GitHub Source Code [GitHub]

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 need to 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 };
Code language: JavaScript (javascript)

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"); } }
Code language: JavaScript (javascript)

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; }
Code language: JavaScript (javascript)

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

Related Posts

#AD Shop Web Developer T-Shirts