Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery keypress() event not firing?

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('???');               }       }); 
like image 430
Mark Struzinski Avatar asked Jan 29 '09 18:01

Mark Struzinski


People also ask

How to use keypress event in jquery?

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

How keypress work?

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 .


2 Answers

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.

like image 58
Nick Berardi Avatar answered Sep 21 '22 18:09

Nick Berardi


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/

like image 20
Jack Lawson Avatar answered Sep 22 '22 18:09

Jack Lawson