Hey guys. I’ve started a mini project today to help some of the javascript lessons sink in. I’ve managed to successfully build a counter but I’m having trouble changing the font colour based on the counter value. I’m trying to change the font colour as follows: orange = 0, red =< -1, green => 1. I’m staring at this code and I can’t work out what I’ve done wrong. Help would be greatly appreciated
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.
Thanks for you help @ilenia, I released i included the changeColor function in the wrong place. I needed to include as part of the updateDisplay function so the colours change when the count is in + & - values. Its working now. Here’s the updated code:
// counter
let count = 0;
let btndisplay = document.querySelector('.counter-value');
let btnadd = document.querySelector('.btn-add');
let btnminus = document.querySelector('.btn-minus');
let btnreset = document.querySelector('.btn-reset');
btnadd.addEventListener("click",()=>{
count++;
updateDisplay();
}) ;
btnminus.addEventListener("click",()=>{
count--;
updateDisplay();
}) ;
function updateDisplay(){
btndisplay.innerHTML = count;
changeColor();
};
btnreset.addEventListener("click", () => {
count = 0;
updateDisplay();
}) ;
updateDisplay();
// change colour based on counter value
function changeColor() {
if (count >= 1){
btndisplay.style.color = 'green';
} else if (count == 0){
btndisplay.style.color = 'orange';
} else if (count <= -1){
btndisplay.style.color = 'red';
}
};