Difference Between Keydown and Keypress in jQuery
When handling keyboard input in jQuery, both keydown and
keypress listen for user actions on the keyboard, but they
differ significantly in the types of keys they detect, the values they
return, and their event-firing order. While keydown
captures the physical pressing of virtually any key on the keyboard,
keypress is specifically designed to respond only to keys
that produce printable character output.
1. Types of Keys Detected
keydown: Fires when any key on the keyboard is pressed. This includes printable characters (letters, numbers, symbols) as well as non-printable and modifier keys, such asShift,Ctrl,Alt,CapsLock, arrow keys, function keys (F1–F12), andEscape.keypress: Fires only when a key that produces a printable character is pressed (such as letters, numbers, punctuation, and theEnterorSpacekey). Modifier keys and navigation keys alone will not trigger akeypressevent in most browsers.
2. Event Execution Order
When a user presses a character key, the browser processes keyboard events in a specific sequence:
keydown(the physical key is initially pressed)keypress(the character value is resolved)keyup(the physical key is released)
If the user holds the key down, both keydown and
keypress will repeat continuously until the key is
released.
3. Returned Values
(which and keyCode)
The values returned by the jQuery event object differ between the two events:
keydownreturns key codes: It identifies the physical key on the keyboard rather than the character itself. For example, pressing eitheraorShift + aproduces the samekeyCode(65).keypressreturns character codes: It identifies the specific character generated. Pressing lowercaseaproduces the ASCII code97, while uppercaseAproduces65.
// Detects any physical key press
$('#inputField').keydown(function(event) {
console.log("Keydown code: " + event.which); // e.g., 65 for both 'a' and 'A'
});
// Detects the resulting character
$('#inputField').keypress(function(event) {
console.log("Keypress character code: " + event.which); // 97 for 'a', 65 for 'A'
});4. Modern Standards and Deprecation
In modern web standards, the native DOM keypress event
has been deprecated. Consequently, modern jQuery applications generally
avoid using .keypress().
To achieve modern, reliable keyboard handling:
- Use
keydownto capture keyboard shortcuts, navigation, or control keys. - Use the
inputevent to capture actual text changes inside input fields or textareas, as it accounts for typing, pasting, and mobile virtual keyboards. - Use the standard
event.keyproperty instead ofevent.whichorevent.keyCodeto directly obtain the character or key name as a string (e.g.,"Enter","a","ArrowUp").