Explain Codes LogoExplain Codes Logo

How can I detect pressing Enter on the keyboard using jQuery?

javascript
event-handling
keyboard-events
jquery
Alex KataevbyAlex Kataev·Jan 10, 2025
TLDR

Detect an Enter key press in jQuery with the .keypress() event and check for event.which === 13. Here's how:

$(selector).keypress(function(event) { if (event.which === 13) { // Enter key detected. It's magic, but don't tell anyone! alert('Shhh! Secret: Enter key was pressed!'); } });

This code snippet listens for a keypress event for the specific element and executes code when the Enter key is pressed.

Best practices and hands-on advice

Consistent cross-browser compatibility

Although .keypress() with event.which provides a normalized approach across multiple browsers, it's good practice to consider older browser support. Use .keydown() as an additional condition:

$(selector).keydown(function(event) { if (event.which === 13 || event.keyCode === 13) { // Compatibility mode: ON! Eleventy-three must be lucky. alert('Enter key was pressed!'); } });

Defining the scope of your Event Listener

Apply the keypress listener to either $(document) for a global scope, or a specific element for localized control, like handling forms:

$('#inputField').keypress(function(event) { if (event.which === 13) { // Now you don't, now you do: Enter on #inputField! } });

Customizing your jQuery methods

For a reader-friendly alternative, create a custom jQuery method such as $.fn.enterKey for explicit handling of Enter key press:

$.fn.enterKey = function (callback) { return this.each(function () { $(this).keypress(function (e) { if (e.which === 13) { callback.call(this, e); // Now serving: Enter key 'ala carte. } }); }); }; // Call the method for specific input field $("#inputField").enterKey(function () { alert('Enter key was exclusive to #inputField!'); });

Performance during high-frequency event handling

If a high-frequency of Enter key presses is expected, debouncing or throttling your handlers can maintain a smooth performance using libraries like lodash:

$('#inputField').keypress(_.debounce(function(event) { if (event.which === 13) { // Throttling Enter key like a boss! } }, 200));

Consider these edge cases and accessibility factors

Keep accessibility in mind

When mapping key actions, consider users with assistive technologies. Your interactions should not interfere with screen readers or keyboard navigation.

Understand the difference between Keydown and Keypress

While keydown registers key presses, keypress acts only when keys are fully pressed. Choose carefully, your users' experience may rely on this.

Manage modifier keys elegantly

Capture Enter in combination with modifier keys (Shift, Ctrl, Alt) by adapting your event handler:

$(selector).keypress(function(event) { var isShiftPressed = event.shiftKey; if (event.which === 13 && isShiftPressed) { // Secret combo unlocked: Shift+Enter! } });