Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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");
    }
}
like image 858
Callum S Avatar asked Apr 22 '20 15:04

Callum S


2 Answers

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);
like image 77
Eugen Sunic Avatar answered Oct 19 '22 09:10

Eugen Sunic


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
   }
 });
like image 28
Blaine McMahon Avatar answered Oct 19 '22 08:10

Blaine McMahon