Which keycode for escape key with jQuery
You can identify the escape key in jQuery by simply declaring the keycode 27. Bind it to the keydown event and compare event.which to 27.
In one beautiful line, you've trapped the escape key in an alert!
Key event basics: KeyDown, KeyUp and company
Using keyup for user intent
We usually prefer the keyup event; why? Let's think about users. Users tend to hold keys down a little longer than expected. With keyup, we get our event when the user lets go:
Why e.key is your new best friend
Your code is not a place for mystery, use e.key for readability. It comes in handy when Aunt Edna uses Internet Explorer:
The enigma of e.which
Remember, e.which is clinging to past glory. If you are coding for tomorrow (and you should), replace that #hasbeen with e.key.
Dealing with the notorious Enter key
To make friends with the Enter key, try this:
Key event handler to the rescue
A key event handler can multitask. Manage those keys like a symphony conductor:
Advanced: Level up your key event handling game
Contextual event handling
Sometimes, attaching the event to the document is a bit…overkill. Close down your modals with Escape? Easy:
Level up your code with named constants
Replace ambiguity with clarity. Named constants turn your code from mysterious novel to an easy-to-follow comic strip:
Cross-browser and legacy friendly
For the good ol' browsers, give event.which one last waltz:
Was this article helpful?