Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Keypress is a confusing event. While keydown and keyup will tell you which specific key on your keyboard is down or just came back up, the keypress event is supposed to tell you what character would appear on the screen, that's why the jquery documentation that you referenced says:</p> <blockquote> <p>For example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress.</p> </blockquote> <p>To make things worse Safari doesn't trigger keypress events for stuff that doesn't write something onto the screen—that’s why arrow keys won't work. Firefox, however, does trigger keypress events for arrow keys. Both are reasonable implementations of the spec, so don’t expect either to change. That's why there was the suggestion to just stick with keydown or keyup.</p> <p>However, it looks like you want to take advantage of how the keypress event repeats (in Firefox) when a key is held down and you want to do this with an arrow key. If that's the case, you need to write a handler that looks at both keydown and keypress. here are the two different ways browsers react to an arrow key being held down:</p> <ul> <li>Firefox registers a keydown event and also repeats keypress events (note: just hitting the key once will register both a keydown and a keypress event)</li> <li>Safari registers a keydown event and repeats the keydown event</li> </ul> <p>A quick hack to make that work reasonably well for arrow keys and get the key repeats to work is:</p> <pre><code>function moveItem(evt) { // do something with `this` and evt.keyCode here... } $(document.documentElement) .keypress(function(evt) { if ($.data(this, '_lastKeyEvent') != 'keydown') { // since firefox will do both a keydown and a keypress for the first // keydown, we ignore the very first keypress moveItem.call(this, evt); } $.data(this, '_lastKeyEvent', 'keypress'); }) .keydown(function(evt) { moveItem.call(this, evt); $.data(this, '_lastKeyEvent', 'keydown'); }); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload