I'm making a keyboard mapper (it basically allows us to check multiple keys that is pressed at the same time), but i have encountered a problem.
the problem is that it wont detect all the keys that is being pressed. for instance: we pressed 10 keys but the code says that only 7 keys are being pressed
, and for instance we pressed 6 keys but the code says that only 4 keys are being pressed
, and yes, it's quite random...
so what is the solution?
NOTE:
addEventListener
and other methodsThank you!
Here are the codes:
var obj = {};
$(document).ready(function() {
document.addEventListener("keydown", function(event) {
obj[event.keyCode] = true;
$("#output").text("" + JSON.stringify(obj));
});
$(document).keyup(function() {
obj[event.keyCode] = false;
$("#output").text("" + JSON.stringify(obj));
});
});
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<p>"PRESS ANY KEY"</p>
<p>KeyDown:
<p id="output"></p>
</p>
<br/>
</body>
</html>
The problem isn't with JavaScript, but with the keyboard itself. It is known as Keyboard Ghosting and there is a great article from Microsoft itself explaining it.
"Ghosting" is the problem that some keyboard keys don't work when multiple keys are pressed simultaneously. The key presses that don't show up on the computer or seem to have disappeared are said to have been "ghosted". On most keyboards, even some that are explicitly marketed as "Anti-Ghosting," this happens with many three key combinations. Imagine playing your favorite video game and not being able to, say, run diagonally and fire your weapon at the same time (say pressing a, w, and g simultaneously). This is a result of the internal design of most existing keyboards, as will be explained below.
Your code is correct and would work with multipress-aware keyboards.