Open Playground
JS TutorialLesson #164

JavaScript Keyboard Events

Keyboard Events happen when the user presses a key on the keyboard:

Keyboard Events happen when the user presses a key on the keyboard:

  • keydown (key is pressed down)
  • keyup (key is released)
  • keypress (deprecated)
keypress only fires for character keys (a or 5), > not for control keys (alt or backspace). > Developers are advised to use keydown or keyup instead.

Share

The keydown Event

Using event.key

Example

Example Code

html
Try it Yourself
const k = document.getElementById("k");

// Let k listen for keydown

k.addEventListener("keydown", function (event) {

// Then display the event.key

  document.getElementById("demo").innerHTML = "You pressed: " + event.key;

});

Key Properties

The KeyboardEvent object provides useful properties to determine which key was involved in the event:

PropertyDescriptionWhen pressing Z
event.keyReturns the value of the key. Can vary based on language settings.Returns z (or Z if shift is held)
event.codeReturns the key code. Constant, regardless of language settings.Always returns "KeyZ"

You can also detect modifier keys using properties like event.ctrlKey, event.shiftKey, event.altKey, > and event.metaKey to implement key combinations (e.g., Ctrl + S).

Detect Enter

Using event.code

Example

Example Code

html
Try it Yourself
const in01 = document.getElementById("in01");

// Let in01 listen for keydown

in01.addEventListener("keydown", function (event) {

// If event.code was "enter", then display text

  if (event.code === "Enter") {

    document.getElementById("demo").innerHTML = "Enter was pressed!";

  }

});

Summary > JavaScript provides keyboard events to detect and handle user input from the keyboard, > enabling interactive web experiences like form validation, game controls, and keyboard shortcuts.

Interactive Code Examples

JS Example 1

html
Try it Yourself
Interactive runnable JavaScript example from EA Academy.
Live Output Preview:

Example 2

html
Try it Yourself
Interactive runnable JavaScript example from EA Academy.
Live Output Preview: