I am trying to fire an event on the right and left arrow key presses with jQuery. Using the following code, I can fire events on any of the alphanumeric keys, but the cursor keys (up, down, left, right) fire nothing. I am developing the site primarily for IE users because it is a line of business app. Am I doing something wrong here?
$('document').keypress(function(e){ switch (e.which) { case 40: alert('down'); break; case 38: alert('up'); break; case 37: alert('left'); break; case 39: alert('right'); break; default: alert('???'); } });
The keypress() method triggers the keypress event, or attaches a function to run when a keypress event occurs. The keypress event is similar to the keydown event. The event occurs when a button is pressed down. However, the keypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC).
The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as Alt , Shift , Ctrl , or Meta .
e.which doesn't work in IE try e.keyCode, also you probably want to use keydown() instead of keypress() if you are targeting IE.
See http://unixpapa.com/js/key.html for more information.
With jQuery, I've done it this way:
function checkKey(e){ switch (e.keyCode) { case 40: alert('down'); break; case 38: alert('up'); break; case 37: alert('left'); break; case 39: alert('right'); break; default: alert('???'); } } if ($.browser.mozilla) { $(document).keypress (checkKey); } else { $(document).keydown (checkKey); }
Also, try these plugins, which looks like they do all that work for you:
http://www.openjs.com/scripts/events/keyboard_shortcuts
http://www.webappers.com/2008/07/31/bind-a-hot-key-combination-with-jquery-hotkeys/
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