-2
<script>
var myVar = setInterval(function(){setColor()},1000);
function setColor(){
var x = document.body;
x.style.backgroundColor = x.style.backgroundColor == "yellow"?"pink":"yellow";
}
</script>

I don't understand in this part:
x.style.backgroundColor == "yellow"?"pink":"yellow";
I try to add some color like this:
x.style.backgroundColor == "yellow"?"pink":"blue":"yellow";
but the script doesn't work.

2 Answers2

4

This is a ternary operator.

x ? y : z

It is saying if x, then y, otherwise z.

In your case, it is saying if the color is yellow, then change it to pink, otherwise change it to yellow. It would cause it to shift back and forth.

You can nest ternary operators, but the syntax gets a little hard to read. It would be better to refactor your code to something like this to add additional colors:

var colors = ["yellow", "pink", "blue"]

x.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];

Anthony L
  • 1,940
  • 8
  • 23
  • Actually it's just saying `"pink"` as in: `"yellow"?"pink":"yellow" == "pink"`. Since `"yellow"` is always `true`. – Spencer Wieczorek Feb 16 '18 at 00:49
  • 4
    @SpencerWieczorek: no, you missed the comparison operator before it. The condition is `x.style.backgroundColor == "yellow"`, not `"yellow"`. – Amadan Feb 16 '18 at 00:51
  • @Amadan Ah your right I thought that was an assignment. – Spencer Wieczorek Feb 16 '18 at 00:51
  • @SpencerWieczorek: There's an assignment too. I guess it's easy to miss since it's almost repeating exactly: `x.style.backgroundColor = x.style.backgroundColor ==`, like the programmer stuttered :P – Amadan Feb 16 '18 at 00:52
-1

hope to help you.

x.style.backgroundColor = x.style.backgroundColor == "yellow"?"pink":"blue":"yellow"; 

change to

x.style.backgroundColor = x.style.backgroundColor == "yellow"?"pink":(x.style.backgroundColor =="pink"?"blue":"yellow");