onKeyPress Vs. onKeyUp and onKeyDown
Solution 1:
NOTE KeyPress
is now deprecated. Use KeyDown
instead.
KeyPress
, KeyUp
and KeyDown
are analogous to, respectively: Click
, MouseUp,
and MouseDown
.
-
Down
happens first -
Press
happens second (when text is entered) -
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 );
}
Solution 2:
Check here for the archived link originally used in this answer.
From that link:
In theory, the
onKeyDown
andonKeyUp
events represent keys being pressed or released, while theonKeyPress
event represents a character being typed. The implementation of the theory is not same in all browsers.
Solution 3:
Most of the answers here are focused more on theory than practical matters and there's some big differences between keyup
and keypress
as it pertains to input field values, at least in Firefox (tested in 43).
If the user types 1
into an empty input element:
The value of the input element will be an empty string (old value) inside the
keypress
handlerThe value of the input element will be
1
(new value) inside thekeyup
handler.
This is of critical importance if you are doing something that relies on knowing the new value after the input rather than the current value such as inline validation or auto tabbing.
Scenario:
- The user types
12345
into an input element. - The user selects the text
12345
. - The user types the letter
A
.
When the keypress
event fires after entering the letter A
, the text box now contains only the letter A
.
But:
- Field.val() is
12345
. - $Field.val().length is
5
- The user selection is an empty string (preventing you from determining what was deleted by overwriting the selection).
So it seems that the browser (Firefox 43) erases the user's selection, then fires the keypress
event, then updates the fields contents, then fires keyup
.