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

223
Views
How to change text color when HTML body background has the same color

I want to change an element's color when the HTML body has the same color for the background.

I use the body element with multiple colors, and the text sometimes was not readable. I need to change the text color, for example, to black when my HTML body loads a white background color.

Here is my code:

var i = 0;

function change() {
  var doc = document.getElementById("background__color");
  var color = ["#15ec34", "#077981", "#8fe607", "#4a66ea"];
  doc.style.backgroundColor = color[i];
  i = (i + 1) % color.length;
}
setInterval(change, 1000);

// Here is the code to change the text color
var doc = document.getElementById("background__color");
var changeColor = document.querySelector("#ch")

if (doc.style.backgroundColor == "black") {
  changeColor.style.color = "#fff";
}
<body id="background__color">
  <div>
    <div class="greeting">
      <p id="ch">Hello world!</p>
    </div>
  </div>
</body>

almost 4 years ago · Santiago Trujillo
1 answers
Answer question

0

put the whole thing inside the function

var i = 0;

function change() {
  var changeColor = document.querySelector("#ch")
  var doc = document.getElementById("background__color");
  var color = ["#15ec34", "#077981", "#8fe607", "#4a66ea", "black"];
  doc.style.backgroundColor = color[i];
  i = (i + 1) % color.length;
  if (doc.style.backgroundColor === "black") {
    changeColor.style.color = "#fff";
  } else {
    changeColor.style.color = "red"
  }
}
setInterval(change, 1000);
#ch {
  font-size: 54px;
}
<body id="background__color">
  <div>
    <div class="greeting">
      <p id="ch">Hello world!</p>
    </div>
  </div>
</body>

You can later change the colour according to your requirements

almost 4 years ago · Santiago Trujillo 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!