I'm attempting to capture arrow key presses in jQuery, but no events are being triggered.
$(function(){ $('html').keypress(function(e){ console.log(e); }); });
This generates events for alphanumeric keys, but delete, arrow keys, etc generate no event.
What am I doing wrong to not be capturing those?
Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes.
To detect the arrow key when it is pressed, use onkeydown in JavaScript. The button has key code. As you know the left arrow key has the code 37. The up arrow key has the code 38 and right has the 39 and down has 40.
Definition and Usagekeydown - The key is on its way down. keypress - The key is pressed down. keyup - The key is released.
Conclusion. We can detect arrow key presses by listening to the keydown event. And in the event listener, we can either check the key or keydown properties of the event object to see which key is pressed. And there you have it.
You should use .keydown()
because .keypress()
will ignore "Arrows", for catching the key type use e.which
Press the result screen to focus (bottom right on fiddle screen) and then press arrow keys to see it work.
Notes:
.keypress()
will never be fired with Shift, Esc, and Delete but .keydown()
will..keypress()
in some browser will be triggered by arrow keys but its not cross-browser so its more reliable to use .keydown()
.More useful information
.which
Or .keyCode
of the event object - Some browsers won't support one of them but when using jQuery its safe to use the both since jQuery standardizes things. (I prefer .which
never had a problem with).ctrl | alt | shift | META
press with the actual captured key you should check the following properties of the event object - They will be set to TRUE if they were pressed: event.ctrlKey
- ctrl event.altKey
- altevent.shiftKey
- shiftevent.metaKey
- META ( Command ⌘ OR Windows Key )Finally - here are some useful key codes ( For a full list - keycode-cheatsheet ):
$(document).keydown(function(e) { console.log(e.keyCode); });
Keypress events do detect arrow keys, but not in all browsers. So it's better to use keydown.
These are keycodes you should be getting in your console log:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With