JQuery arrow keys

I am trying to capture arrow keys in jQuery, but no events are fired.

$(function(){ $('html').keypress(function(e){ console.log(e); }); }); 

This generates events for alphanumeric keys, but delete, arrow keys, etc. do not generate any event.

What am I doing wrong to not capture them?

+51
javascript jquery keypress
Oct 13 '13 at 16:08
source share
5 answers

Here is an example: JSnippet DEMO keydown () vs keypress ()

You must use .keydown() because .keypress() ignores the "arrows", in order to catch the key type, use e.which

Click the results screen to focus (bottom right of the violin screen), and then press the arrow keys to see how it works.

Notes:

  • .keypress() will never be launched using Shift, Esc and delete, but .keydown() will.
  • In fact .keypress() in some browser will be triggered by the arrow keys, but it is not a cross browser, so its a more reliable way to use .keydown() .

Additional useful information

  1. You can use the .which or .keyCode of the event object. Some browsers do not support one of them, but when using jQuery it is safe to use both, since jQuery standardizes everything. (I prefer .which never run into a problem).
  2. If you want to detect the ctrl / alt / shift keystroke using the actual captured key, you must check the .ctrlKey , .altKey and .shiftKey properties of the event object - they will be TRUE if they were used.
  3. Finally, here are some useful key codes (Full list - keycode-cheatsheet ):

    • Enter: 13
    • Up: 38
    • Down: 40
    • Right: 39
    • Left: 37
    • Esc: 27
    • SpaceBar: 32
    • Ctrl: 17
    • Alt: 18
    • Shift: 16
+142
Oct 13 '13 at 16:16
source share
 $(document).keydown(function(e) { console.log(e.keyCode); }); 

Keypress events detect arrow keys, but not in all browsers. Therefore, it is better to use keydown.

These are the key codes that you should receive in your console log:

  • left = 37
  • up = 38
  • right = 39
  • down = 40
+23
Oct 13 '13 at 16:13
source share

You can check if the arrow key is pressed:

 $(document).keydown(function(e){ if (e.keyCode > 36 && e.keyCode < 41) alert( "arrowkey pressed" ); }); 

jsfiddle demo

+7
Dec 18 '14 at 3:18
source share

Please refer to the link from jQuery

http://api.jquery.com/keypress/

It says

A keypress event is dispatched to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifiers and non-printable keys, such as Shift, Esc, and delete, trigger key change events, but not keypress events. Other differences between the two events may occur depending on the platform and browser.

This means that you cannot use keypress in the case of arrows.

+2
Jul 24 '14 at 16:32
source share
 $(document).on( "keydown", keyPressed); function keyPressed (e){ e = e || window.e; var newchar = e.which || e.keyCode; alert(newchar) } 
0
May 4 '17 at 6:58 a.m.
source share



All Articles