'How can I get auto-repeated keydown events in Firefox when arrow keys are held down?

I've got several editable divs. I want to jump through them by pressing arrow keys (38 and 40).

Firefox 3 on Mac OS and Linux won't repeat the events on holding the key. Obviously only keypress events are supported for repetition. As the keys 38 and 40 are only supported on keydown I'm kind of stuck.



Solution 1:[1]

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;
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1