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
Examples of keys that don't produce a character value are modifier keys such as Alt , Shift , Ctrl , or Meta . Warning: Since this event has been deprecated, you should use beforeinput or keydown instead.
The keypress() method in jQuery triggers the keypress event whenever browser registers a keyboard input. So, Using keypress() method it can be detected if any key is pressed or not.
Warning The keypress event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type. When in editing contexts, authors can subscribe to the beforeinput event instead.
keydown - The key is on its way down. keypress - The key is pressed down. keyup - The key is released.
Use keydown instead of keypress, some browsers does not fire keypress when an "special key (like arrows)" are pressed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With