How can I get automatically recurring events in Windows when I press the arrow keys?

I have some editable div s. I want to jump over them by pressing the arrow keys (38 and 40).

Firefox 3 on Mac OS and Linux will not repeat events while holding the key. Obviously, only keypress events are supported for repetition. Since the keys 38 and 40 are only supported on keydown , I'm kind of stuck.

+4
source share
2 answers

You can use keypress and check e.keyCode == 38.40 instead of e.which or e.charCode This is consistent between Mac and Win.

 $('#test').bind($.browser.mozilla ? 'keypress' : 'keyup', function(e) { if ( (e.which || e.keyCode) == 40 ) { /* doSometing() */ } }); 

See JavaScript Madness: Keyboard Events (3.2. Return Values ​​in Character Events) and event.keyCode on MDC.

0
source

Yes, you're stuck. You can emulate the behavior you want using timers until you get the appropriate keyup , but this obviously will not use the user's computer keyboard repeat settings.

The following code uses the above method. The code that you want to handle with key change events (both real and simulated) should go to handleKeyDown :

 var keyDownTimers = {}; var keyIsDown = {}; var firstKeyRepeatDelay = 1000; var keyRepeatInterval = 100; function handleKeyDown(keyCode) { if (keyCode == 38) { alert("Up"); } } function simpleKeyDown(evt) { evt = evt || window.event; var keyCode = evt.keyCode; handleKeyDown(keyCode); } document.onkeydown = function(evt) { var timer, fireKeyDown; evt = evt || window.event; var keyCode = evt.keyCode; if ( keyIsDown[keyCode] ) { // Key is already down, so repeating key events are supported by the browser timer = keyDownTimers[keyCode]; if (timer) { window.clearTimeout(timer); } keyIsDown[keyCode] = true; handleKeyDown(keyCode); // No need for the complicated stuff, so remove it document.onkeydown = simpleKeyDown; document.onkeyup = null; } else { // Key is not down, so set up timer fireKeyDown = function() { // Set up next keydown timer keyDownTimers[keyCode] = window.setTimeout(fireKeyDown, keyRepeatInterval); handleKeyDown(keyCode); }; keyDownTimers[keyCode] = window.setTimeout(fireKeyDown, firstKeyRepeatDelay); keyIsDown[keyCode] = true; } }; document.onkeyup = function(evt) { evt = evt || window.event; var keyCode = evt.keyCode; var timer = keyDownTimers[keyCode]; if (timer) { window.clearTimeout(timer); } keyIsDown[keyCode] = false; }; 
+1
source

All Articles