20 min25 XP

Keyboard Events

Keydown, Keyup, and Key Detection

Step 1 of 5

Understanding Keyboard Events

Keyboard events detect when users press, hold, or release keys on their keyboard. They're essential for text input, keyboard shortcuts, and game controls!

Main Keyboard Events:

  • keydown: Fires when a key is pressed down
  • keyup: Fires when a key is released
  • keypress: Fires when a key is pressed (deprecated)

Real-World Examples

Keyboard events enable many powerful features:

  • Search boxes that filter as you type
  • Keyboard shortcuts (Ctrl+S to save)
  • Form validation while typing
  • Game controls (WASD for movement)
  • Auto-complete suggestions
  • Character counters
// Basic keyboard event
document.addEventListener('keydown', function(event) {
console.log('Key pressed:', event.key)
})

The event.key property tells you which key was pressed!