Home > Net >  Why is the background color of my HTML element not changing in JavaScript when the conditions are me
Why is the background color of my HTML element not changing in JavaScript when the conditions are me

Time:08-19

I am trying to change the background color of a wrapper div depending on the value of the counter so if positive I am changing the background to green and if its negative I'm giving red color and if not any it is dark blue. here is my code below.

let counter = 0;
let counterWrapper = document.querySelector('.counter');
let btnIncrease = document.getElementById('btn-increase');
let btnDecrease = document.getElementById('btn-decrease');
let counterValue = document.getElementById('counter-value');
let bgColor = counterWrapper.style.backgroundColor;


btnIncrease.addEventListener('click', function(){
    counter  ;
    counterValue.textContent = counter;
    changeColor();
});

btnDecrease.addEventListener('click', function(){
    counter--;
    counterValue.textContent = counter;
    changeColor();
});
     
// bgColor =  counter >= 1 ? "#14C38E" : (counter < 0 ? "#E95454" : "#2A2252");

function  changeColor(){
    if (counter > 0)
    bgColor = "#14C38E";
    else if (counter < 0)
    bgColor = "#E95454";
    else
    bgColor = "#2A2252";

}

CodePudding user response:

You need to update the background property of the div, update your function as follow:

function  changeColor(){
    if (counter > 0)
        bgColor = "#14C38E";
    else if (counter < 0)
        bgColor = "#E95454";
    else
        bgColor = "#2A2252";

    counterWrapper.style.backgroundColor = bgColor;
}

CodePudding user response:

the problem is that bgColor is considered as a string not an object. to get the result you want you have to change bgColor to

let bgColor = counterWrapper.style;

function  changeColor(){
if (counter > 0)
    bgColor.backgroundColor = "#14C38E";
    else if (counter < 0)
    bgColor.backgroundColor = "#E95454";
    else
    bgColor.backgroundColor = "#2A2252";
}
  • Related