Detect Which Key Was Pressed in JavaScript

Use a keyboard event together with event.key to identify the key a user pressed. This is clearer and more portable than the old numeric keyCode or which values.

Key details will appear here.
const input = document.querySelector('#key_input');
input.addEventListener('keydown', (event) => {
  console.log(event.key);
});
Table of Contents

Use event.key for the Meaning of the Key Top ↑

event.key tells you the key value that the user intended, such as "a", "Enter", "Escape" or "ArrowLeft". This is the right default for shortcuts, form behavior and most keyboard interactions.

Use event.code for Physical Key Position Top ↑

event.code identifies a physical keyboard position, such as "KeyA". This is useful for game-like controls but can differ from what the key produces on non-QWERTY layouts, so do not use it when you need the character the user actually typed.

Legacy keyCode and which Top ↑

Older plus2net examples used keyCode, which and String.fromCharCode(). These numeric-key patterns are deprecated. When maintaining old code, understand them; when writing new code, use event.key or event.code.

// Legacy code - avoid in new projects
const numericCode = event.keyCode || event.which;

// Modern
const keyName = event.key;

Detecting Arrow Keys Top ↑

For arrow-key controls, use event.key with keydown. You can also review the older keyboard-event sequence in keydown, keyup and the legacy keypress page.

← Event Handling Mouseover and mouseout →




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