I’ve been trying to make a game with arrow key movement and want to make, "when all arrow keys are not pressed then the key = nothing,". So I need a way of detecting this, I’ve tried to use Keyup but it doesn’t work.
I tried using other questions on stack overflow but nothing I find is as related to the title as I thought it would’ve been. If it helps I can add some sample code below.
var key = "";
onkeydown = e => {
key = e.code;
};
This makes it set to the code but I want it to set back to nothing when the user releases the key.
// ive tried this keyup method buts it so buggy
onkeyup = e => {
key = "";
}
This is something but I can’t use it because of all the downsides, I will add one more thing but as an example of what I’m trying to achieve, and I have no idea what I’m really doing.
var ifAllKeysArePressed; // I dont know what it should equal or anything
// I want the value to be boolean
setInterval(() => {
if(!ifAllKeysArePressed) {
key = "";
};
}, Infinity);
>Solution :
You can store all currently pressed keys in a Set.
const pressed = new Set, p = document.querySelector('p');
document.addEventListener('keydown', e => {
pressed.add(e.code);
p.textContent = '';
});
document.addEventListener('keyup', e => {
pressed.delete(e.code);
if (!pressed.size) p.textContent = 'No keys down';
});
<p></p>