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);
});
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.
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
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);
});
Use event.preventDefault() only when your interface deliberately replaces a browser behavior. Avoid overriding familiar keyboard navigation unnecessarily.
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.
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.