Keyboard support makes a web app faster for experienced users and essential for people who cannot use a mouse. JavaScript tells you about every key press through keydown and keyup events. Each event tells you which character was typed, which physical key was pressed and whether Shift, Ctrl, Alt or Cmd were held. In this lesson you will inspect these events, then build real shortcuts such as Ctrl+S to save and arrow keys to move between buttons.
In this lesson you will learn
keydownandkeyup, and whykeypressis out of date- The difference between
e.keyande.code - Modifier keys and
e.repeat - Writing shortcuts with
preventDefault() - Not breaking typing, and arrow-key navigation
You should know events and the DOM.
What a Key Event Tells You
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Keyboard event inspector</title>
<style>
body { font-family: sans-serif; margin: 12px; font-size: 14px; }
input { padding: 6px 8px; font: inherit; width: 260px; }
table { border-collapse: collapse; margin-top: 8px; font-family: monospace; }
td, th { border: 1px solid #ccc; padding: 3px 8px; text-align: left; }
th { background: #f1f3f4; }
</style>
</head>
<body>
<label>Click here and press some keys:<br>
<input id="box" placeholder="try a, A, Shift+1, Enter, arrows"></label>
<table>
<tr><th>event</th><th>key</th><th>code</th><th>shift</th><th>ctrl/meta</th><th>repeat</th></tr>
<tbody id="rows"></tbody>
</table>
<script>
const rows = document.getElementById("rows");
function show(e) {
const tr = document.createElement("tr");
[e.type, JSON.stringify(e.key), e.code, e.shiftKey, e.ctrlKey || e.metaKey, e.repeat]
.forEach(v => { const td = document.createElement("td"); td.textContent = v; tr.append(td); });
rows.prepend(tr);
while (rows.children.length > 4) rows.lastChild.remove(); // keep the newest 4
}
const box = document.getElementById("box");
box.addEventListener("keydown", show);
box.addEventListener("keyup", show);
// Show two sample presses so the table is not empty at first
box.dispatchEvent(new KeyboardEvent("keydown", { key: "A", code: "KeyA", shiftKey: true }));
box.dispatchEvent(new KeyboardEvent("keydown", { key: "!", code: "Digit1", shiftKey: true }));
</script>
</body>
</html>
Result
keydownfires when a key goes down, and again and again if it is held.keyupfires once when it is released. The oldkeypressevent is deprecated, so do not use it.e.keyis the value the key produces:"a","A","!","Enter"or"ArrowUp". It changes with Shift and with the keyboard layout.e.codeis the physical key, such as"KeyA"or"Digit1", whatever is printed on it. Shift+1 gives key"!"but code"Digit1".e.shiftKey,e.ctrlKey,e.altKeyande.metaKey(the Cmd key on a Mac) are true while those keys are held.e.repeatis true for the automatic repeats while a key is held down.- Click in the box inside the frame and press keys to see your own events.
| Use | Check | Why |
|---|---|---|
| Shortcuts by letter (Ctrl+S) | e.key | Matches the letter the user sees |
| Game controls (WASD) | e.code | Same position on every layout |
| Enter, Escape, arrows | e.key | Clear names such as "Escape" |
Building Shortcuts
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Keyboard shortcuts</title>
<style>
body { font-family: sans-serif; margin: 12px; font-size: 14px; }
kbd { border: 1px solid #aaa; border-bottom-width: 2px; border-radius: 4px; padding: 0 5px; background: #fafafa; font-size: 12px; }
textarea { width: 100%; max-width: 380px; height: 54px; font: inherit; margin-top: 6px; }
#status { color: #00796b; min-height: 1.4em; margin: 6px 0; }
.list { display: flex; gap: 6px; margin-top: 6px; }
.list button { padding: 6px 10px; border: 1px solid #999; background: white; border-radius: 6px; }
.list button:focus { outline: 3px solid #1e88e5; }
</style>
</head>
<body>
<p>Shortcuts: <kbd>Ctrl</kbd>+<kbd>S</kbd> save · <kbd>/</kbd> focus the box · <kbd>Esc</kbd> clear · <kbd>←</kbd><kbd>→</kbd> move between buttons</p>
<textarea id="note" placeholder="Type a note..."></textarea>
<div id="status" aria-live="polite"></div>
<div class="list" id="tabs"><button>Home</button><button>Lessons</button><button>Quiz</button></div>
<script>
const note = document.getElementById("note");
const status = document.getElementById("status");
const say = msg => (status.textContent = msg);
document.addEventListener("keydown", e => {
const typing = e.target.matches("input, textarea");
// Ctrl+S (or Cmd+S on a Mac): stop the browser's own "Save page" and use ours
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "s") {
e.preventDefault();
say("Saved " + note.value.length + " characters.");
return;
}
// "/" jumps to the box, but only when the user is not already typing
if (e.key === "/" && !typing) {
e.preventDefault();
note.focus();
say("Focused the note box.");
return;
}
if (e.key === "Escape" && typing) {
e.target.value = "";
say("Cleared.");
}
});
// Arrow keys move focus between buttons in a group
const buttons = [...document.querySelectorAll("#tabs button")];
document.getElementById("tabs").addEventListener("keydown", e => {
const i = buttons.indexOf(document.activeElement);
if (e.key === "ArrowRight") buttons[(i + 1) % buttons.length].focus();
if (e.key === "ArrowLeft") buttons[(i - 1 + buttons.length) % buttons.length].focus();
});
say("Click inside this frame first, then try the shortcuts.");
</script>
</body>
</html>
Result
- One
keydownlistener ondocumenthandles shortcuts for the whole page. (e.ctrlKey || e.metaKey)accepts Ctrl on Windows and Linux and Cmd on a Mac.e.key.toLowerCase()also matches when Caps Lock is on.e.preventDefault()stops the browser’s own action. Without it, Ctrl+S would open the “Save page” dialog.- The / shortcut checks
typingfirst, so users can still type a slash inside the text box. Single-key shortcuts must never fire while the user is typing. - The arrow-key handler moves focus around the group with
% buttons.length, so it wraps from the last button back to the first. - Click inside the frame first so it receives the key presses, then try the shortcuts.
Make shortcuts discoverable
Show shortcuts with <kbd> elements, as this demo does, or in a help panel opened with ?. Avoid taking over keys the browser or screen readers rely on, such as Tab and Ctrl+W.
Common Mistakes
- Using
e.keyCodeore.which. These numbers are deprecated; usee.keyore.code. - Firing single-letter shortcuts while the user types in an input or textarea.
- Checking
e.key === "s"only, which fails when Caps Lock or Shift is on. - Listening for keys on elements that cannot get focus, such as a plain
<div>. Listen ondocument, or addtabindex="0".
Practice Exercises
Exercise 1. Close an open dialog when the user presses Escape.
Show answer
document.addEventListener("keydown", e => {
if (e.key === "Escape") document.querySelector(".dialog.open")?.classList.remove("open");
});
A real <dialog> element opened with showModal() closes on Escape by itself.
Exercise 2. Move a box with the arrow keys, 10 pixels per press, without scrolling the page.
Show answer
let x = 0, y = 0;
const moves = { ArrowLeft: [-10, 0], ArrowRight: [10, 0], ArrowUp: [0, -10], ArrowDown: [0, 10] };
document.addEventListener("keydown", e => {
const m = moves[e.key];
if (!m) return;
e.preventDefault(); // stop the page from scrolling
x += m[0]; y += m[1];
box.style.transform = `translate(${x}px, ${y}px)`;
});
Frequently Asked Questions
Why do I not get key events while typing Bangla with an input method?
Many input methods build characters in steps, called composition. During composition, e.isComposing is true and e.key may be "Process". Skip shortcuts while e.isComposing is true, and use the input event to read the text that was typed.
Can I detect a key combination like Ctrl+Shift+K?
Yes: check e.ctrlKey && e.shiftKey && e.key.toLowerCase() === "k". Avoid combinations the browser already uses, since some, like Ctrl+W, cannot be overridden.
Summary
- Use
keydownandkeyup;keypressandkeyCodeare deprecated. e.keyis the character or key name;e.codeis the physical key.- Check modifier properties, call
preventDefault()for your shortcuts and skip them while the user is typing. - Arrow keys with wrap-around focus make groups of buttons keyboard friendly.
