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");
}
}
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);
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
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With