In the following code:
$(document).keypress(function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 40) {
alert("down pressed");
} else if (code == 38) {
alert("up pressed");
}
});
I'm trying to detect if the down key or up key is pressed. Why isn't it working?
Fiddle /
I'm in chrome
In the following code:
$(document).keypress(function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 40) {
alert("down pressed");
} else if (code == 38) {
alert("up pressed");
}
});
I'm trying to detect if the down key or up key is pressed. Why isn't it working?
Fiddle http://jsfiddle.net/K9uDn/10/
I'm in chrome
Share Improve this question edited Jul 1, 2013 at 19:23 SB2055 asked Jul 1, 2013 at 19:18 SB2055SB2055 12.9k37 gold badges104 silver badges205 bronze badges 6 | Show 1 more comment4 Answers
Reset to default 21Use keydown instead of keypress, some browsers does not fire keypress when an "special key (like arrows)" are pressed
jQuery's keypress
method isn't very stable. Use on('keydown')
instead.
See: http://jsfiddle.net/K9uDn/9/
Here's the Fiddle of a fixed version of the javascript code with extra buttons trapped using a switch/case statement
$(document).on('keydown',function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
switch (code){
case 34:
alert("Page down pressed");
break;
case 33:
alert("Page up pressed");
break;
case 40:
alert("Down pressed");
break;
case 38:
alert("Up pressed");
break;
case 37:
alert("Left pressed");
break;
case 39:
alert("Right pressed");
break;
}
on('keyup') does not work in IE. Not in version 9 at least.
keypress
tokeydown
orkeyup
(and if I remove thoseself.gotIt()
andself.forgotIt()
). I strongly recommend that you usekeyup
orkeydown
anyways, even if you didn't have this issue... it's much better, and everything is predictable with it.keydown
should replacekeypress
as well. – MiJyn Commented Jul 1, 2013 at 19:24keyCode
andcharCode
withwhich
, so you don't need to check them both. Just usewhich
. – crush Commented Jul 1, 2013 at 19:26keypress
is more of an IE thing. – crush Commented Jul 1, 2013 at 19:29