Explain Codes LogoExplain Codes Logo

Jquery Event Keypress: Which key was pressed?

javascript
keypress
event-handling
jquery
Anton ShumikhinbyAnton Shumikhin·Oct 1, 2024
TLDR

To pinpoint which key was pressed in a jQuery keypress event, utilize event.which. This grabs the key's character code to convert it to the respective character through String.fromCharCode.

Sample code:

$(document).keypress(function(event) { console.log('You pressed: ' + String.fromCharCode(event.which)); });

Alternatively, event.key provides a readable format without the need for conversion.

Peek under the hood: keypress events

Good ol' keypress events play a crucial role in your web applications. Their usage becomes an easy piece of cake once you become familiar with the quirks related to differentiating one key from another and ensuring cross-browser compatibility.

What's the big fuss about event.which?

Long story short, jQuery utilizes event.which to nullify the confusion around keystroke detection across different browsers. It's the knight in shining armor, returning the character code for both regular and special characters, uniformly across all modern browsers.

The elder sibling: event.keyCode

Despite being deprecated, event.keyCode still has its perks for those legacy browsers (You know who you are!). Keep this in your back pocket as a strategy for those rare, desperate times.

Triggering the Magic

To execute a specific action on the Enter key press (key code 13):

$(document).keypress(function(event) { if (event.which === 13) { console.log('Enter key pressed, make a wish! 🌠'); } });

For those days when you need a bit more magic, jQuery UI steps in with $.ui.keyCode constant map. You can now use $.ui.keyCode.ENTER as the "Open Sesame" for identifying Enter keypresses.

Advanced Stops & Go's

Let's delve into advanced options and tackling those moment when you want the default key action to stop in its tracks.

Slamming the breaks with event.preventDefault()

The power to halt the default behavior is as easy as calling event.preventDefault():

$(document).keypress(function(event) { if (event.which === 13) { event.preventDefault(); console.log('Enter key pressed, but default behavior has been stopped 💥'); } });

Selecting Actions for Keys

jQuery's bind function lets you tie multiple keys to different actions:

$(document).bind('keypress', function(event) { if (event.which === 13) { // Establish the submit action console.log('13 enters the game. Ready to submit!') } });

Passing on the touch in interactions

To make interactive elements respond to specific values, use callback functions. Meet doSomethingWith(this.value):

$('#myInput').keypress(function(event) { if (event.which === 13) { doSomethingWith(this.value); console.log(this.value + ' has now entered the game. Let the actions begin!'); } });

Special attention: edge cases, simulations & more!

Life would be so much easier without special cases right? Let's dive in.

Testing browser compatibility

You'll want to test your keypress events on a range of devices and browsers. Because, well, responsive design and accessibility. Cough... yeah, you know what we mean.

Simulating those pesky keypresses

Sometimes you just want to pretend to press a key – like for testing purposes. jQuery UI's sweet jquery.simulate.js plugin has got you covered:

// Using jquery.simulate.js for 🎬 Take 1 $('.myInputField').simulate('keypress', { keyCode: $.ui.keyCode.ENTER });

The event's secret info stash

e.altKey, e.ctrlKey, and e.shiftKey are like keys to secret shortcut combinations. Don't forget to explore the e parameter for more gems!