The jQuery keypress event fires repeatedly when a key is held, but not on all keys

This is probably the intended behavior, or at least not the jQuery / js issue, but I would like some clarification if any.

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 an example in jQuery docs: http://api.jquery.com/keypress/

When you press the left or right cursor (or many other keys, such as A,E,[, etc.), the event fires and you get a good log message in the console. Everything is perfect and as intended. However, now try holding the key down - after a short pause, you will see that the keydown event fires several times when you hold the key, however if you try to press p (or, for example, a j ), it will fire only once.

I am testing this using FF 9.0.1 and Mac OSX 10.7.1 and jQuery 1.7.1.

Is it by design, is it a browser-specific function, or is it related to the OS or even the keyboard itself? Also, does anyone have a list of keys that will be repeated, and keys that will not?

As far as usage is concerned, there is not one really - it just appeared when I was tying the animation to pressing the cursor and started to see more strange behavior when I pressed the key. My workaround was to instead use the keyup() and preventDefault() event in the keydown() event for the keys in which I was installed to stop the cursors scrolling the screen.

UPDATE: It appears that in the keypress event keyCode is always 0 for most letters, which may have something to do with why I thought that the handler only runs once. After some testing, I see duplicate log entries, for example for cursors. If you check the jQuery API page and use the demo version, it demonstrates the behavior that I described: http://api.jquery.com/keypress/

Still can't explain it myself: /

+7
source share
3 answers

The behavior varies between browsers and operating systems. The following page details the topic of auto-repeat key events in section 2.2:

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

+5
source

This problem has existed for a long time, but I think I discovered the fix only now. It seems to work fine

 $("#search_query").keyup(function(event) { //this will void fake keypresses if(event.charCode == 0 && event.keyCode == 0) { return false; } //place the rest of you code here }); 
+1
source

Also - for everyone who views this post: try the keydown method

Keypress will fire several times ... keydown will not

http://jquerymobile.com/demos/1.0a2/experiments/api-viewer/docs/keypress/index.html

0
source

All Articles