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>
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