CodeBlanks Logo Icon CodeBlanks

Keyboard events

JavaScript course · Intermediate · Lesson 34/134

Learn to capture pressed keys with keydown and keyup.

keydown and keyup

Keyboard events come in two main forms: keydown fires when a key is pressed, keyup when it is released. If you hold the key down, keydown repeats.

document.addEventListener('keydown', (event) => {
  console.log('Pressed:', event.key);
});
document.addEventListener('keyup', (event) => {
  console.log('Released:', event.key);
});

You may see keypress in old code; but this event is deprecated and not used in new code. Use keydown for new work.

Reading the key with event.key

For keyboard events, the event.key property gives the value of the pressed key. Letters return lowercase like 'a' or 'b'; special keys return readable names like 'Enter', 'Escape', 'ArrowUp'.

document.addEventListener('keydown', (event) => {
  if (event.key === 'Enter') {
    console.log('Enter was pressed');
  }
});

It is case-sensitive: 'a' and 'A' are different values. With Shift, you get 'A'. So always compare against the exact value.

Exercise Log the pressed key on keydown

Add an arrow function handler with document.addEventListener('keydown', ...). The handler parameter should be event and it should call console.log(event.key) inside.

Show example solution
document.addEventListener('keydown', (event) => {
  console.log(event.key);
});

Test yourself

  1. Which event fires repeatedly while a key is held down?

    • keyup
    • change
    • input
    • keydown
    Show answer

    keydown — Correct! keydown repeats while the key is held down.

  2. Complete the keydown listener

    document.addEventListener('____', (event) => {
      console.log(event.key);
    });
    Show answer
    document.addEventListener('keydown', (event) => {
      console.log(event.key);
    });
  3. Match the keyboard concepts

    keydown
    On key press
    keyup
    On key release
    event.key
    Pressed key value
    'Enter'
    Confirm key

All lessons in Intermediate