Course contentsShow
← Web Development
Lesson 731 of 2,98213. DOM EventsFree lesson

Keyboard Events: keydown, keyup, keypress

Handle keyboard input with keydown and keyup events, and understand why keypress is deprecated.

Keyboard Events: keydown, keyup, keypress

You'll learn how to respond to keyboard input using event listeners and why one of these events is no longer recommended.

What Are Keyboard Events?

Keyboard events fire when users interact with their keyboard. Just like mouse events detect clicks and movement, keyboard events detect when keys are pressed and released. These events let you build interactive features like form validation, keyboard shortcuts, search filters, and games.

The Three Keyboard Events

keydown fires when a key is first pressed down. It repeats continuously if you hold the key down, making it perfect for detecting when typing begins or for game controls that need continuous input.

keyup fires when a key is released. This happens once per key press, making it ideal for detecting when a user has finished pressing a key.

keypress is a deprecated event that used to fire between keydown and keyup for character keys only. Modern browsers still support it, but you should avoid using it because it doesn't work consistently across browsers and doesn't detect all keys (like arrows or function keys).

Why Use keydown and keyup Instead?

Think of it like a doorbell: keydown is when your finger touches the button, keyup is when you lift your finger off. The deprecated keypress tried to detect "the moment of ringing" but couldn't handle all types of buttons reliably.

The keydown and keyup events work with all keys on the keyboard, including modifiers (Shift, Ctrl), function keys (F1-F12), and navigation keys (arrows, Home, End).

When to Use Which

Use keydown when you need to detect typing as it happens or for real-time controls. Use keyup when you want to wait until the user has finished pressing a key, often better for form validation.

Key Takeaway: Use keydown and keyup for modern keyboard input handling; avoid the deprecated keypress event as it's inconsistent and doesn't support all keys.