1

My code is

$('input').live('keypress', function(event) {
   if (event.keyCode === 37) console.log("left key pressed");
    else console.log("some other key press");
});

Please see http://jsfiddle.net/4RKeV/

This detects keypresses, but not the left keypress (keyCode 37). How can I detect left keypress?

3

2 Answers 2

3

In short: don't use the keypress event. Use keydown or keyup instead.

The keypress event is not covered by any official specification. As such, keypress does not have well-defined behavior, will not work the same way across browsers, and will act capriciously and unpredictably. (Read more [quirksmode.org])

As an alternative to keypress, you should use one of these events:

  • keydown [w3c spec] -- This triggers when a key is pressed down and continues to trigger while the key is held down.
  • keyup [w3c spec] -- This triggers when the key is lifted up.

I would probably fix it by using keydown because it is probably closer to what you were expecting keypress to do:

$('input').live('keydown', function(e) { 
   if (e.which === 37) { console.log("left key pressed"); }
   else { console.log("some other key press"); }
}); 

P.S. I changed e.keyCode to e.which, because it is more cross-browser compliant.

2
  • Great. So why doesn't keypress detect it anyway?
    – Randomblue
    Aug 30, 2011 at 21:39
  • @Randomblue it's just not a standardized event, so its implementations vary. Some browsers simply don't trigger keypress with arrow keys. Aug 30, 2011 at 21:42
3

Change your binding event to keyup:

$('input').live('keyup', function(event) {
  if (event.keyCode === 37) console.log("left key pressed");
    else console.log("some other key press");
});
3
  • It all comes down to whatever browser implementation it is. In IE9 at least, the event simply isnt triggered on that key press.
    – Tejs
    Aug 30, 2011 at 21:40
  • Hum. But isn't jQuery meant to harmonize this?
    – Randomblue
    Aug 30, 2011 at 21:41
  • It's probably attached a handler to the keypress event sure (across browser implementations). However, it's probably IE9 which doesnt even invoke the event to reach the handler. jQuery just makes it easy to attach to the event.
    – Tejs
    Aug 30, 2011 at 21:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.