Every key the visitor presses fires a keydown event. A listener on document hears every key, wherever the focus is. event.key names the key: "Escape", "Enter", "a", "/".
The focus is the one field or button that gets what the visitor types. element.focus() moves it there, and the check prints (focused) beside it. event.target is the element that had the focus when the key was pressed.
After your listener, the browser still does its own job for the key, like typing it into the focused field. event.preventDefault() stops that. Here is a shortcut on another key:
const help = document.querySelector("#help");
document.addEventListener("keydown", (event) => {
if (event.key === "?") {
help.classList.toggle("hidden");
}
});
The check presses / (it prints the key as \/), then Escape, clicks the Cart button and types a review. Your page must show:
> press \/ → field "Search": "" (focused)
> press Escape → section "Cart" leaves the screen
> click "Cart (0)" → section "Cart" comes back
> type "Holds 1/2 liter" into "Your review"
→ field "Your review": "Holds 1/2 liter" (focused)
Your task: the cart panel and its Cart button are given. Add a keydown listener: Escape hides the cart panel; / moves the focus to the search box without typing the slash, but only when the visitor isn't typing in a field.
Assignment
Follow the Coding Tutorial to add two keyboard shortcuts: Escape closes the cart, and / jumps to the search box.
Hint
Compare event.key with the key's name. For the slash, also check that event.target doesn't match "input, textarea", and stop the browser's own action before you move the focus.
Free plan: 30 tutor messages. PRO is unlimited.
