Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the background color of my HTML element not changing in JavaScript when the conditions are met

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

}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading