Search code examples
javascriptkeydown

How to detect and map many keys being pressed at once


I am using the keydown and keyup event to detect key presses. But when I press 2 or 3 or more keys and hold them down, most of the time it won't recognize any more keys pressed after, until I stop holding down the keys. I am looking to detect any number of keys pressed at once.

It seems all of the other posts I've looked at are only about figuring out how to map multiple keys pressed at once, but not about this particular issue I've run into.

This is how I map key presses in my code:

// a map of press-able keys
const key = {
  w: false,
  a: false,
  s: false,
  d: false
};

document.addEventListener('keydown', function(e) {

  if (key[e.key.toLowerCase()] != undefined) {
    key[e.key.toLowerCase()] = true;
  }

});

document.addEventListener('keyup', function(e) {

  if (key[e.key.toLowerCase()] != undefined) {
    key[e.key.toLowerCase()] = false;
  }

});

For example, if I held down W, A, S, and D simultaneously, most of the time, it would only recognize the first 2 or 3 I pressed, and ignore the last 1 or 2 (key.a and key.w might be true, but key.s and key.d might be false, even though they're being pressed down).

Is there something wrong with this implementation? Or is there a limit to the keydown event I haven't been able to find in searching? What is a potential solution for being able to detect many keys at once?


Solution

  • Keyboard ghosting: is a phenomenon in which a computer keyboard fails to accurately register simultaneous key presses, often affecting gaming and typing experiences. Anti-ghosting technology is employed to mitigate this issue by ensuring the correct recognition of multiple key inputs.

    Microsoft provides an interactive demo, you can use it to test your keyboard. https://www.microsoft.com/applied-sciences/projects/anti-ghosting-demo