Two events describe the keyboard: keydown (a key goes down, repeats while held) and keyup (a key is released).
<input id="field" placeholder="Type here">
<p id="out"></p>
<script>
document.querySelector("#field").addEventListener("keydown", event => {
document.querySelector("#out").textContent = `You pressed: ${event.key}`;
});
</script>
event.key and event.code
| Property | Meaning | Example (the A key) |
|---|---|---|
event.key | the character or name the key produces | "a" or "A" |
event.code | the physical key on the keyboard | "KeyA" |
Use key when you care about what was typed or named keys like "Enter", "Escape", "ArrowDown". Use code for game-style controls (WASD) that should work on any keyboard layout.
Common keys
if (event.key === "Enter") { ... }
if (event.key === "Escape") { ... }
if (event.key === "ArrowLeft" || event.key === "ArrowRight") { ... }
if (event.key === " ") { ... } // the space bar
Modifier keys
event.ctrlKey, event.shiftKey, event.altKey and event.metaKey (Cmd on a Mac) tell you if a modifier was held.
<p>Press Ctrl + S (or Cmd + S) in the result panel</p>
<p id="out"></p>
<script>
document.addEventListener("keydown", event => {
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "s") {
event.preventDefault(); // stop the browser's own "save page"
document.querySelector("#out").textContent = "Custom save shortcut!";
}
});
</script>
Submit on Enter
<input id="todo" placeholder="New task, then press Enter">
<ul id="list"></ul>
<script>
document.querySelector("#todo").addEventListener("keydown", event => {
if (event.key === "Enter" && event.target.value.trim()) {
const li = document.createElement("li");
li.textContent = event.target.value.trim();
document.querySelector("#list").append(li);
event.target.value = "";
}
});
</script>
Holding a key
keydown repeats while the key is held. event.repeat is true for the repeats, so you can ignore them.
keypress is deprecated
You may see keypress in old code. It is deprecated. Use keydown and keyup.
Accessibility
Do not take over common keys unnecessarily. Custom shortcuts should not clash with the browser or screen readers, and widgets like menus and dialogs have expected keys (Escape to close, arrows to move). See Keyboard Interaction.