I've created an app trying to learn keydown event listeners. When I press arrow keys, divs' background color changes. However, I'd like to know how to cancel the effect, ie. return to the default background color, when I press the same key again.
document.addEventListener("keydown", pressKeyOn);
const arUp = document.querySelector(".ar-up");
const arLeft = document.querySelector(".ar-left");
const arRight = document.querySelector(".ar-right");
const arDown = document.querySelector(".ar-down");
function pressKeyOn(e) {
console.log(e);
if (e.keyCode === 38) {
arUp.style.backgroundColor = "red";
} else if (e.keyCode === 40) {
arDown.style.backgroundColor = "green";
} else if (e.keyCode === 39) {
arRight.style.backgroundColor = "navy";
} else if (e.keyCode === 37) {
arLeft.style.backgroundColor = "violet";
}
}
So how to return to the original (eg. yellow background), if I press respective arrow key?
CodePudding user response:
You can create a class for all the colors and toggle it on every click.
const arUp = document.querySelector(".ar-up");
const arLeft = document.querySelector(".ar-left");
const arRight = document.querySelector(".ar-right");
const arDown = document.querySelector(".ar-down");
function pressKeyOn(e) {
if (e.keyCode === 38) arUp.classList.toggle("red")
else if (e.keyCode === 40) arDown.classList.toggle("green")
else if (e.keyCode === 39) arRight.classList.toggle("navy")
else if (e.keyCode === 37) arLeft.classList.toggle("violet")
}
document.addEventListener("keydown", pressKeyOn);
.red{ background-color: red;}
.green{ background-color: green;}
.navy{ background-color: navy;}
.violet{ background-color: violet;}
<div class="ar-up">ar-up</div>
<div class="ar-left">ar-left</div>
<div class="ar-right">ar-right</div>
<div class="ar-down">ar-down</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Here is a more generic version using classList.toggle
const colors = {
"ArrowUp": "red",
"ArrowDown": "green",
"ArrowLeft": "navy",
"ArrowRight": "violet"
}
document.addEventListener("keydown", function(e) {
const key = e.key;
if (colors[key]) document
.querySelector(`.${key}`)
.classList
.toggle(colors[key])
})
.red {
background-color: red;
}
.green {
background-color: green;
}
.navy {
background-color: navy;
}
.violet {
background-color: violet;
}
<div class="ArrowUp">ar-up</div>
<div class="ArrowLeft">ar-left</div>
<div class="ArrowRight">ar-right</div>
<div class="ArrowDown">ar-down</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>