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.
const input = document.querySelector('#key_input');
input.addEventListener('keydown', (event) => {
console.log(event.key);
});
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.
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.
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;
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 →
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.