Determine Pressed Key Using jQuery Event Object

When handling keyboard interactions in web applications, identifying the specific key pressed by a user is essential for form handling, navigation, and shortcuts. This article explains how to detect pressed keys using the jQuery Event object, focusing on the standard event.which property, modern alternatives like event.key, and practical implementation examples.

Using the event.which Property

jQuery normalizes keyboard events across different browsers by providing the event.which property. This property returns the numeric ASCII or keyCode representing the pressed key, eliminating discrepancies between older implementations of event.keyCode and event.charCode.

You can attach an event listener using .on() with keyboard events such as keydown, keyup, or keypress:

$(document).on('keydown', function(event) {
    console.log("Key code pressed: " + event.which);
});

Checking for Specific Keys

To trigger specific logic when a particular key is pressed, compare event.which against the key's numeric code.

Common key codes include:

  • Enter: 13
  • Escape: 27
  • Spacebar: 32
  • Left Arrow: 37
  • Up Arrow: 38
  • Right Arrow: 39
  • Down Arrow: 40

Example of capturing the "Enter" key:

$('#search-input').on('keydown', function(event) {
    if (event.which === 13) {
        event.preventDefault(); // Prevent standard form submission
        console.log("Enter key pressed. Executing search...");
    }
});

Using Modern Standard Properties: event.key and event.code

While event.which is reliable in jQuery for numeric codes, modern JavaScript standards have deprecated numeric key codes in favor of string-based values. The jQuery Event object wraps the native browser event, allowing direct access to event.key and event.code.

  • event.key: Returns the character value produced by the key (e.g., "Enter", "a", "ArrowUp").
  • event.code: Returns the physical key identifier on the keyboard regardless of keyboard layout (e.g., "KeyA", "Enter", "Space").

Example using event.key:

$(document).on('keydown', function(event) {
    if (event.key === "Escape") {
        console.log("Escape key detected. Closing modal.");
    }
});

Using event.key is more readable than matching numeric codes and avoids the need to memorize or look up integer values. For backwards compatibility in legacy systems, event.which remains the conventional jQuery approach.