Question

I've been noticing some odd behaviour with keyboard input in JavaScript. I may be missing something really obvious here, but are there some kind of rules regarding which keys are allowed to be pressed simultaneously?

I'm using boolean variables to hold state for each of four keys as follows, this allows for many simultaneous key presses (hardware permitting):

var up = false, left = false, right = false, space = false;

function keydown(e) {
    if (e.keyCode == 32)
        space = true;
    if (e.keyCode == 38)
        up = true;
    if (e.keyCode == 37)
        left = true;
    if (e.keyCode == 39)
        right = true;
}

function keyup(e) {
    if (e.keyCode == 32)
        space = false;
    if (e.keyCode == 38)
        up = false;
    if (e.keyCode == 37)
        left = false;
    if (e.keyCode == 39)
        right = false;
}

On two machines I've tried the following jsfiddle allows you to press space, up and right simultaneously, but not space, up and left, for example. On those two machines it's doing the same in Chrome, FF and IE. On a third machine it works flawlessly and I can hold all 4 keys simultaneously.

Now presumably this is hardware related, but my main question is why there is a difference in the operation of the left and the right keys? It seems inconsistent and I'm sure there is a valid reason why it's the way it is.

http://jsfiddle.net/SYs5b/

(You have to click within the results pane to get the events firing)

Was it helpful?

Solution

In order to save money, keyboard manufacturers often put many keys on the same bus. This prevents multiple keys in the same region of the keyboard from being pressed simultaneously. Sometimes it even prevents more than 2 keys at all from across the whole keyboard being pressed at once. Often the shift, ctrl, and alt keys are not within this limitation, so you can hold shift and press 2 other keys at once and it will still work fine.

Even high-end gaming keyboards often have a similar hardware limitation, although the cap is much higher so that it is unlikely to be reached during the normal course of gaming.

This is also known as "ghosting", when keys you press seem not to register.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top