Jquery Event Keypress: Which key was pressed?
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:
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):
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()
:
Selecting Actions for Keys
jQuery's bind
function lets you tie multiple keys to different actions:
Passing on the touch in interactions
To make interactive elements respond to specific values, use callback functions. Meet doSomethingWith(this.value)
:
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:
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!
Was this article helpful?