Setting style.background as a var doesn't work

Viewed 103

I modified this working Javascript code by setting style.background as var "x" and it doesn't toggle anymore. Where is the problem?

<script>
var myVar = setInterval(setColor, 300);
 
function setColor() {
/* This commented-out code works.
  var x = document.body;
  x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";
  */
  var x = document.body.style.backgroundColor;  // not working
  x = x == "yellow" ? "pink" : "yellow";
}
</script>
2 Answers

That's because in the original code:

function setColor() {
  var x = document.body;
  x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";
}

x is a reference of document.body, nevertheless, in your code, when you do:

x = x == "yellow" ? "pink" : "yellow";

x is not equal to a reference of document.body anymore, now it is a string, either pink or yellow. So, x will not change the html because it is only a string variable.

If you want the code to work, you need to add this code behind x declaration.

document.body.style.backgroundColor = x

Your assigning value to variable "x", not document.body.style.backgroundColor, don't store it in a variable.

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

Related