The following is a code I have written to change a grid color to indigo upon clicking it, then removing the color upon the second click. However, I do not know how to rewrite the if-else statement using a ternary operator.
const grid1=document.querySelector(".cell01")
grid1.addEventListener("click", (e)=>{
console.log(e);
if (grid1.style.backgroundColor) {
grid1.style.backgroundColor = "";
} else {
grid1.style.backgroundColor = "indigo";
}
})
Thank you for your help in advance (:
Update
Thanks for the answers! But now I have one more inquiry -- I wanted to try different ways of rewriting the same code, and came up with this:
grid1.style.backgroundColor=(grid1.style.backgroundColor!=true) ? "indigo" : "";
It did exactly what I wanted with the expression (grid1.style.backgroundColor==false)
, but not in the case of the former. Is there a reason why?
Straightforward translation into a ternary:
grid1.style.backgroundColor = grid1.style.backgroundColor ? "" : "indigo";