jQuery Keypress Arrow Keys
$(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:
- left = 37
- up = 38
- right = 39
- down = 40
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.- Actually
.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
- You can use
.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). - To detect a
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
- ctrlevent.altKey
- altevent.shiftKey
- shiftevent.metaKey
- META ( Command ⌘ OR Windows Key )
Finally - here are some useful key codes ( For a full list - keycode-cheatsheet ):
- Enter: 13
- Up: 38
- Down: 40
- Right: 39
- Left: 37
- Esc: 27
- SpaceBar: 32
- Ctrl: 17
- Alt: 18
- Shift: 16
You can check wether an arrow key is pressed by:
$(document).keydown(function(e){
if (e.keyCode > 36 && e.keyCode < 41)
alert( "arrowkey pressed" );
});
jsfiddle demo