Callum S
Callum S

Reputation: 221

How can I fire a event when a key is pressed down

I have tried the code before, but when I hold down W it repeats the code, but I want to so if I hold it down, it will only execute the code one.

window.addEventListener("keydown", checkKeyPressW, false);

var player = document.getElementById("player");

var leftMarginCounter = 0;
var bottomMarginCounter = 0;

var leftMarginCounterToString = "";

function checkKeyPressA_D(keyPressed) {
    if(keyPressed.keyCode == "97") {
        if(player.style.marginLeft != "0px") {
            leftMarginCounter = leftMarginCounter - 1;
            leftMarginCounterToString = leftMarginCounter.toString();
            leftMarginCounterToString = leftMarginCounterToString + "px";
            player.style.marginLeft = leftMarginCounterToString;
        }
    }
    else if(keyPressed.keyCode == "100") {
        if(player.style.marginLeft != "1316px") {
            leftMarginCounter = leftMarginCounter + 1;
            leftMarginCounterToString = leftMarginCounter.toString();
            leftMarginCounterToString = leftMarginCounterToString + "px";
            player.style.marginLeft = leftMarginCounterToString;
        }
    }
};

function checkKeyPressW(keyPressedW) {
    if(keyPressedW.keyCode == "87") {
        console.log("Pressed w");
    }
}

Upvotes: 5

Views: 279

Answers (2)

EugenSunic
EugenSunic

Reputation: 13693

JS demo: https://jsfiddle.net/utnqeLmf/1/

Code:

 window.addEventListener("keydown", checkKeyPressW,  {
      once : true
 });

From the docs

once A Boolean indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.

EDIT

If you want to avoid continuous key consoling when having the key pressed then change the event to keyup

window.addEventListener("keyup", checkKeyPressW);

Upvotes: 5

Blaine McMahon
Blaine McMahon

Reputation: 197

There is a property called repeat that returns true if the key is being held down

document.addEventListener('keydown', (event) => {
   if(event.repeat) {
      // key is being held down
   } else {
      // key is being pressed
   }
 });

Upvotes: 2

Related Questions