Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onKeyPress Vs. onKeyUp and onKeyDown

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?

like image 563
instantsetsuna Avatar asked Aug 03 '10 13:08

instantsetsuna


People also ask

What is the difference between the Keydown and Keyup events?

The keydown event is triggered first when user presses a key. The keyup event is triggered last when user releases a key. In between, the keypress event is triggered.

Should I use keypress or Keydown?

The keydown event is fired when a key is pressed. Unlike the keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.

What does Onkeydown mean?

The onkeydown attribute fires when the user is pressing a key (on the keyboard).

What is Onkeyup used for?

The onkeyup attribute fires when the user releases a key (on the keyboard).


2 Answers

NOTE KeyPress is now deprecated. Use KeyDown instead.

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 ); }
like image 74
Robusto Avatar answered Sep 19 '22 05:09

Robusto


Check here for the archived link originally used in this answer.

From that link:

In theory, the onKeyDown and onKeyUp events represent keys being pressed or released, while the onKeyPress event represents a character being typed. The implementation of the theory is not same in all browsers.

like image 38
dcp Avatar answered Sep 21 '22 05:09

dcp