Reputation: 1
<main>
<div class=counter-container>
<h1 class="counter-value">(..)</h1>
<div class="btn-container">
<button class="btn-add">+</button>
<button class="btn-minus">-</button>
<button class="btn-reset">Reset</button>
</div>
</div>
</main>
<script src="counter.js"></script>
I'm pretty new to JavaScript. Today I started a mini project to help the 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’m doing wrong. Help would be greatly appreciated :)
Here is my current 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;
};
btnreset.addEventListener("click", () => {
count = 0;
updateDisplay()
}) ;
updateDisplay();
// change colour of font based on counter value
function changeColor() {
if(count >= 0){
btndisplay.style.color = 'green';
} else if (count == 0){
btndisplay.style.color = 'orange';
} else if (count <= -1){
btndisplay.style.color = 'red';
}
};
changeColor();
Upvotes: 0
Views: 71
Reputation: 196002
You only call the changeColor
once at start.
You need to call it after every change, so include it in updateDisplay
.
(additionally you need to change the first if
in your check, because it is if(count >= 0)
when it should be if(count >= 1)
// 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 of font 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';
}
};
<div class="counter-value"></div>
<button class="btn-add">add</button>
<button class="btn-minus">minus</button>
<button class="btn-reset">reset</button>
Upvotes: 1