Hello! Everyone please help me ! my function not working!
<script>
function addColor () {
var udata = document.getElementById("centerbox1").value;
if (udata > 0) {
document.getElementById("centerbox1").style.color = '#99C262';
}
else
if (udata < 0)
{
document.getElementById("centerbox1").style.color = '#FF6C60';
}
else
if (udata === 0)
{
document.getElementById("centerbox1").style.color = '#1456a8';
}
};
</script>
<div class="containerbox">
<div id="centerbox1">
<div class="value">
<p> <span>1</span>
<br/><span>Utilisation</span>
</p>
</div>
</div>
</div>
In this else if statement,
you can do the same thing but change backgroundColor to color.
2 Likes
thanks @shimphillip for the answer
else if (udata < 0) { document.getElementById(âcenterbox1â).style.color = â#FF6C60â; }
or apply both:
let element = document.getElementById(âcenterbox1â);
element.style.color = "somecolor";
element.style.backgroundColor = "somecolor";
1 Like
thanks @JordanMarsh but my function is not working i donât where is wrong!
Can you paste your changed code?
this is last version
<script>
function addColor () {
var udata = document.getElementById("centerbox1").value;
if (udata > 0) {
document.getElementById("centerbox1").style.color = '#99C262';
}
else
if (udata < 0)
{
document.getElementById("centerbox1").style.color = '#FF6C60';
}
else
if (udata === 0)
{
document.getElementById("centerbox1").style.color = '#1456a8';
}
};
</script>
Sorry I hadnât actually looked over the code much.
So you have a few problems. The first is you canât access the value of any element except input elements. And you need to target it directly. So you would have to change your
<span>1</span>
to
<input id="centerbox1" value = 1>
make sure to remove the id from your div when doing this to avoid errors
then in your JavaScript you have a function but you never call it. So above
function addColor () {
you would want to call
addColor();
alternatively you could convert it to ES6 and do:
const addColor = () => {function here};
Otherwise it should work. To save yourself some computing time you can save the element like I showed above and reference it directly instead of re-calling the DOM everytime.
let element = document.getElementById(âcenterbox1â);
element.style.color = "somecolor";
element.style.backgroundColor = "somecolor";
1 Like
Finally my function is working ! Thank you for spending time with me!
1 Like