Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
Setting style.background as a var doesn't work

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>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!