Yes, you're kind of stuck. You could emulate the behaviour you want by using timers until you receive the corresponding keyup
, but this obviously won't use the user's computer's keyboard repeat settings.
The following code uses the above method. The code you want to handle keydown events (both real and simulated) should go in 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;
};