0

I'm using keydown and keyup events to track which keys are currently being pressed, but the results are somewhat incosistent. If I'm holding left arrow (37) and up arrow (38) and try to hold space (32) it doesn't get detected. However if I'm holding right arrow (39) instead of left, I can press space and it works just fine. Is the implementation wrong or could it be a bug in the browser? I've tested on Chrome and Firefox and got the same results.

Here's my code:

let activeKeys = [];

window.addEventListener('keydown', (e) => {
  activeKeys[e.keyCode] = true;
  updateList();
});

window.addEventListener('keyup', (e) => {
  activeKeys[e.keyCode] = false;
  updateList();
});

let updateList = () => {
  let div = document.getElementById('test');
  let html = '';

  for (let keyCode in activeKeys) {
    if (activeKeys[keyCode]) html += `<p>${keyCode}</p>`;
  }

  div.innerHTML = html;
}
<div id="test"></div>
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • maybe this helps? https://stackoverflow.com/questions/5203407/how-to-detect-if-multiple-keys-are-pressed-at-once-using-javascript – Amacado Jul 17 '20 at 21:22
  • Also good to know: https://gaming.stackexchange.com/questions/20449/keyboard-multiple-key-press-problem – Roko C. Buljan Jul 17 '20 at 21:26

0 Answers0