views:

34

answers:

3

I have a regular onkeydown event handler that fires a function, like this:

window.onkeydown = onKeyDown;

It essentially works, but it only captures 1 key in Firefox. Then I have to release it and press again.

Google chrome offers me a continuous grab, so I wonder if this is by choice.

+1  A: 

Have you tried the keypress event? The keypress event is fired after keydown if the key is held down.

CD Sanchez
+1  A: 

What if you try something like this:

var iskeydown = 0;
var samplecount = 0;

function onKeyDown() {
    iskeydown = 1;
    while (iskeydown) continuous();
}

function onKeyUp() {
    iskeydown = 0;
    alert(samplecount);
}

function continuous() {
    samplecount = samplecount + 1;
}

window.onkeydown = onKeyDown;
window.onkeyup = onKeyUp;

Made better:

var iskeydown = 0;
var samplecount = 0;

function onKeyDown() {
    iskeydown = 1;
    continuous();
}

function onKeyUp() {
    iskeydown = 0;
    alert(samplecount);
}

function continuous() {
    if (iskeydown == 1) {
         samplecount = samplecount + 1;
         setTimeout("continuous()",200);
    }
}

window.onkeydown = onKeyDown;
window.onkeyup = onKeyUp;
Fosco
Doesn't seem a great idea: it will place unnecessary stress on the JavaScript runtime, could produce the "This script is taking a long time" warning and could prevent the browser from handling new key events.
Tim Down
Yeah.. updated it to use setTimeout..
Fosco
+1  A: 

I guess you must be using a Mac or Linux, because in Windows, Firefox does support auto-repeated keydown events. In other operating systems, however, you only get auto-repeated keypress events when you hold a key down. In summary, if you can, use the keypress event.

See Jan Wolter's excellent article on JavaScript key events for more information.

Tim Down