Skip to content

JavaScript Tutorial Events

JavaScript Keyboard Events

Lesson 114 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

Two events describe the keyboard: keydown (a key goes down, repeats while held) and keyup (a key is released).

index.html
HTML
<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

PropertyMeaningExample (the A key)
event.keythe character or name the key produces"a" or "A"
event.codethe 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

script.js
JS
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.

index.html
HTML
<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

index.html
HTML
<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.