5

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");
    }
}
2
  • 1
    It has a built in option to fire only once: window.addEventListener("keydown", checkKeyPressW, {once:true, capture:false});
    – Gavin
    Commented Apr 22, 2020 at 15:47
  • why not using keyup event. it fires once at the end when you release key. Commented Apr 22, 2020 at 15:48

2 Answers 2

5

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);
1
  • Sorry, I did not specify that correctly, I want it so it would only register it once until the key was pressed back up again
    – Callum S
    Commented Apr 22, 2020 at 15:52
2

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
   }
 });

Not the answer you're looking for? Browse other questions tagged or ask your own question.