JavaScript keydown Event

The keydown event fires when a key is pressed. It works for character keys, navigation keys and modifier keys, making it the usual choice when an interface must react immediately to keyboard input.

Press a key in the field.

const input = document.querySelector('#keydownInput');
input.addEventListener('keydown', (event) => {
  console.log(event.key);
});
Table of Contents

When keydown Fires Top ↑

The event fires before the browser completes the key’s default action. If the user holds a key down, browsers can generate repeated keydown events.

Open the keydown demo

Reading the Pressed Key Top ↑

Use event.key for the key value. For example, arrow keys report ArrowLeft, ArrowRight, ArrowUp and ArrowDown.

document.addEventListener('keydown', (event) => {
  if (event.key === 'Escape') {
    console.log('Escape pressed');
  }
});

Detect arrow keys with keydown

Handling Held Keys Top ↑

Check event.repeat when an action should occur only once even if a key is held down.

document.addEventListener('keydown', (event) => {
  if (event.repeat) return;
  console.log(event.key);
});

Preventing a Default Key Action Top ↑

Use event.preventDefault() only when your interface deliberately replaces a browser behavior. Avoid overriding familiar keyboard navigation unnecessarily.

keydown and the Current Input Value Top ↑

The original plus2net demo shows an important timing detail: during keydown, the character that triggered the event may not yet be reflected in an input’s value. If your purpose is to react to the updated text value, use the input event or keyup.

Compare with the legacy keypress page and continue to keyup.

← Event Handling




Subscribe to our YouTube Channel here



plus2net.com










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer