Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 427
SB2055 Avatar asked Jul 01 '13 19:07

SB2055


People also ask

Is keypress deprecated in jQuery?

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.

How does jQuery detect keyboard press?

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.

Is keypress deprecated?

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.

What is Keyup and Keydown in jQuery?

keydown - The key is on its way down. keypress - The key is pressed down. keyup - The key is released.


1 Answers

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

like image 63
Aguardientico Avatar answered Oct 13 '22 10:10

Aguardientico