SB2055 SB2055 - 7 days ago 6
Javascript Question

jQuery up key / down key keypress detection not working?

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

Answer

Use keydown instead of keypress, some browsers does not fire keypress when an "special key (like arrows)" are pressed