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>