Add Keyboard Shortcuts

Sam’s shopping list now checks everything Sam types, and in Exercise: Validate the Rating Form, the family’s rating form got its rules too. Getting to the Item box is another matter. After a click on Add the usual milk, the focus leaves Item (in Chrome and Edge, it stays on the button), so Sam reaches for the mouse or presses Shift+Tab over and over. On many sites, pressing / puts the cursor in the search box.

In this lesson, you’ll find out which events a keypress sends and what they tell you about the key. Then you’ll write that / shortcut for Sam’s list and make sure it never gets in the way of typing. Start by listening to the keyboard.

Hear Every Key on the Page

A shortcut has to hear its key wherever the focus is on the page, so start with where key events go.

Pressing a key fires a keydown event, and letting it go fires a keyup event. Both fire on the element that has the focus, such as the box Sam is typing in or the button Sam last clicked. When nothing has the focus, they fire on the page’s <body>. Like click and input, they bubble up through every parent, all the way to document, the object that stands for the whole page.

So one listener on document hears every key, wherever the focus is. Add this listener to the end of main.js for now:

Language: JavaScript Filename: kitchen/main.js
document.addEventListener("keydown", (event) => {
  console.log(event.key, event.code, event.shiftKey);
});

Save and click the page’s heading so that no box has the focus. Then press A, then Shift+A, then /, then Esc, and look at the Console. Here’s what a US keyboard logs when you use the left Shift:

Language: Program Output
a KeyA false
Shift ShiftLeft true
A KeyA true
/ Slash false
Escape Escape false

Other layouts and the right Shift show different code values, such as ShiftRight. Each line shows three properties of one keydown event. The first, event.key, says what the key means: the character it types, such as a, A, or /, or a name for a key that types nothing, such as Shift or Escape. The second, event.code, names the physical key, so it’s KeyA with or without Shift.

The third, event.shiftKey, is true while Shift is held. That’s why Shift+A logged two lines: Shift went down first and fired its own keydown. Then A fired one with shiftKey set.

Three more Boolean flags work the same way: ctrlKey, altKey (Option on macOS), and metaKey (Cmd on macOS, the Windows key on Windows). Hold a key down, and keydown fires again and again, with event.repeat set to true after the first one.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.