yan
yan

Reputation: 5

How can I rewrite this code using a ternary operator?

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?

Upvotes: 0

Views: 386

Answers (5)

Nadeem Taj
Nadeem Taj

Reputation: 1

By using a ternary operator, you can simply the change the code as per your control names.

var button = document.querySelector("button");

button.addEventListener("click", function() {
    const curColour = document.body.style.backgroundColor;

    document.body.style.backgroundColor = curColour === 'red' ? 'blue' : 'red';
});

Upvotes: 0

Shubham
Shubham

Reputation: 31

You can try this:

grid1.style.backgroundColor = grid1.style.backgroundColor ? "" : "indigo";

Checkout below reference to learn more about ternary operator https://www.freecodecamp.org/news/ternary-operator-javascript-if-statement-tutorial/

Upvotes: 1

Charlie
Charlie

Reputation: 23768

grid1.style.backgroundColor = grid1.style.backgroundColor ? '' : 'indigo'

Upvotes: 1

SuperStormer
SuperStormer

Reputation: 5387

Straightforward translation into a ternary:

grid1.style.backgroundColor = grid1.style.backgroundColor ? "" : "indigo"; 

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386519

You could asssign with taking a property from an object.

backgroundColor = { indigo: '', '': 'indigo' }[backgroundColor];

Upvotes: 0

Related Questions