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?
In short: don’t use the
keypressevent. Usekeydownorkeyupinstead.The
keypressevent is not covered by any official specification. As such,keypressdoes 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
keydownbecause it is probably closer to what you were expectingkeypressto do:P.S. I changed
e.keyCodetoe.which, because it is more cross-browser compliant.