Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to detect if no key is currently being pressed down on the keyboard?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// 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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading