Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
194
rated 0 times [  199] [ 5]  / answers: 1 / hits: 117292  / 11 Years ago, sun, october 13, 2013, 12:00:00

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?


More From » jquery

 Answers
127

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:




  1. .keypress() will never be fired with Shift, Esc, and Delete but .keydown() will.

  2. 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




  1. 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).

  2. 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:


  3. 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



[#75018] Friday, October 11, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
americar

Total Points: 631
Total Questions: 107
Total Answers: 103

Location: Luxembourg
Member since Tue, Jan 25, 2022
2 Years ago
;