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 as Shift, Ctrl, Alt, CapsLock, arrow keys, function keys (F1–F12), and Escape.
  • keypress: Fires only when a key that produces a printable character is pressed (such as letters, numbers, punctuation, and the Enter or Space key). Modifier keys and navigation keys alone will not trigger a keypress event in most browsers.

2. Event Execution Order

When a user presses a character key, the browser processes keyboard events in a specific sequence:

  1. keydown (the physical key is initially pressed)
  2. keypress (the character value is resolved)
  3. 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:

  • keydown returns key codes: It identifies the physical key on the keyboard rather than the character itself. For example, pressing either a or Shift + a produces the same keyCode (65).
  • keypress returns character codes: It identifies the specific character generated. Pressing lowercase a produces the ASCII code 97, while uppercase A produces 65.
// 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 keydown to capture keyboard shortcuts, navigation, or control keys.
  • Use the input event to capture actual text changes inside input fields or textareas, as it accounts for typing, pasting, and mobile virtual keyboards.
  • Use the standard event.key property instead of event.which or event.keyCode to directly obtain the character or key name as a string (e.g., "Enter", "a", "ArrowUp").