onKeyPress Vs. onKeyUp and onKeyDown

instantsetsuna picture instantsetsuna · Aug 3, 2010 · Viewed 287.7k times · Source

What is the difference between these three events? Upon googling I found that:

  • The onKeyDown event is triggered when the user presses a key.
  • The onKeyUp event is triggered when the user releases a key.
  • The onKeyPress event is triggered when the user presses & releases a key (onKeyDown followed by onKeyUp).

I understand the first two, but isn't onKeyPress the same as onKeyUp? Is it possible to release a key (onKeyUp) without pressing it (onKeyDown)?

This is a bit confusing, can someone clear this up for me?

Answer

Robusto picture Robusto · Aug 3, 2010

KeyPress, KeyUp and KeyDown are analogous to, respectively: Click, MouseUp, and MouseDown.

  1. Down happens first
  2. Press happens second (when text is entered)
  3. Up happens last (when text input is complete).

The exception is webkit, which has an extra event in there:

keydown
keypress
textInput     
keyup

Below is a snippet you can use to see for yourself when the events get fired:

window.addEventListener("keyup", log);
window.addEventListener("keypress", log);
window.addEventListener("keydown", log);

function log(event){
  console.log( event.type );
}