Meet the Keyboard Events

To work with keyboards in a HTML document, there are three events that you will need to familiarize yourself with. Those events are:

  • keydown
  • keypress
  • keyup

Given what these events are called, you probably already have a vague idea of what each event does. The keydown event is fired when you press down on a key on your keyboard. The keyup event is fired when you release a key that you just pressed. Both of these events work on any key that you interact with.

The keypress event is a special bird. At first glance, it seems like this event is fired when you press down on any key. Despite what the name claims, the keypress event is fired only when you press down on a key that displays a character (letter, number, etc.). What this means is somewhat confusing, but it makes sense in its own twisted way.

If you press and release a character key such as the letter y, you will see the keydown, keypress, and keyup events fired in order. The keydown and keyup events fire because the y key is simply a key to them. The keypress event is fired because the y key is a character key. If you press and release a key that doesn’t display anything on the screen (such as the spacebar, arrow key, function keys, etc.), all you will see are the keydown and keyup events fired.

This difference is subtle but very important when you want to ensure your key presses are actually overheard by your application.

Say What?

It is weird that an event called keypress doesn’t fire when any key is pressed. Maybe this event should be called something else like characterkeypress, but that is probably a moo point.

Get hands-on with 1200+ tech skills courses.