Javascript – jQuery keypress event fires repeatedly when key is held – but not on all keys

javascriptjquerykeypress

This is probably intended behaviour or atleast not a jQuery / js issue but I'd like some clarification if there's any to be had.

Take the following:

$(document).bind('keypress', function(e){
    switch(e.keyCode)
    {
        case 37:
            console.log('left cursor keydown, will fire on hold');
            break;
        case 39:
            console.log('right cursor keydown, will fire on hold');
            break;
        case 80:
            console.log('p will only fire once per press!');
            break;
    }
});

You can also play with the example at jQuery's docs: http://api.jquery.com/keypress/

When a left or right cursor is pressed (or many other keys such as A,E,[, etc), the event fires and you get a nice log message in the console. All fine & as intended. However, now try holding the key down – after a brief pause you will see that the keydown event fires multiple times when you hold the key, however if you try hitting a p (or, for instance, a j), it will only fire once.

I'm testing this using FF 9.0.1 and mac OSX 10.7.1 and jQuery 1.7.1.

Is this by design, is it a browser-dependant feature, or is it to do with the OS, or even the keyboard itself? Also has anyone got a list of keys that will repeat and keys that will not?

As far as the use case goes, there isn't one really – this just cropped up when I was binding an animation to a cursor press and started seeing wierd behaviour when the key was pressed. My workaround was to use the keyup() event instead, and preventDefault() on the keydown() event for the keys I was insterested in, to stop the cursors scrolling the screen.

UPDATE:
Seems that on the keypress event, keyCode is always 0 for most letters, which might have something to do with why I thought the handler only fired once. After some more testing I see the repeated log entries like for cursors. If you check the jQuery API page though, and use the demo on that, it exhibits the behaviour I was describing: http://api.jquery.com/keypress/

Still can't explain that myself :/

Best Answer

Behaviour varies between browsers and operating systems. The following page covers the topic of auto-repeated key events in detail in section 2.2:

http://unixpapa.com/js/key.html