ARCS2016
ARCS2016

Reputation: 25

Multiple Key Inputs Fail After 4 Keys Held

Sort of new to programming, made a test demo to figure out how key inputs worked. The demo looked good until I started noticing that some keys were not being registered. I just pressed and held q -> w -> e -> r -> t and the t did not show up in the output unless I released the other keys. Here is my code, it is pretty basic.

var p1 = document.getElementById("p1");
var keys = [];

document.addEventListener("keydown", function(e) {
  keys[e.keyCode] = true;
  update();
});

document.addEventListener("keyup", function(e) {
  keys[e.keyCode] = false;
  update();
});

function update() {
  console.log(keys);

  p1.innerText = "";

  for (i = 0; i < keys.length; i++) { //checks the entire array and outputs the arr position, which is the keycode, if true
    if (keys[i]) {
      p1.innerText += i + " | ";
    }
  }
}
<p id="p1">testing</p>

Any ideas on why the 5th input sometimes doesn't map? Are there ways to get around this?

Upvotes: 1

Views: 56

Answers (1)

elixenide
elixenide

Reputation: 44833

This is hardware-specific and depends on the "rollover" limitations imposed by your OS, keyboard, and possibly the software (browser) in question. For example, on my system, your code correctly triggers for q+w+e+r+t+y, but not a seventh key. So, it appears your max is 4, while mine is 6.

To answer your specific questions:

Any ideas on why the 5th input sometimes doesn't map?

In short, because something—probably the keyboard itself, but possibly other hardware in your computer or software—is disregarding the additional keys.

Are there ways to get around this?

Not reliably, in the sense that it may work for some users, but you can't deploy code like this on the web and expect it to work for all users. Some older hardware may support only 2 keys at once.

Upvotes: 1

Related Questions