I'm practicing my JavaScript skills, I've been mastering a simple incrementing counter function that I seem to have mastered, so today I wanted to take that script to the next level and decrement the value,
Here is my problem, when I click add number and then continue clicking minus sign, the first click still adds a value before > The countdown is on, what am I missing to avoid this happening?
My code is as follows:
const output = document.getElementById('counter'); const addBtn = document.getElementById('btn-add'); const minusBtn = document.getElementById('btn-minus'); let number = 0; function increment() { output.innerHTML = number++; } function decrement() { output.innerHTML = number--; } addBtn.addEventListener('click', increment); minusBtn.addEventListener('click', decrement);
<div class="container"> <h1>Increment and Decrement Numbers</h1> <div class="output"> <div> <p>Your total count is: <span id="counter"></span></p> </div> <div class="buttons"> <button id="btn-add">+</button> <button id="btn-minus">-</button> </div> </div> </div>
Use
number
When incrementing thenumber
variable, this statement returns the value before the increment. If you want to get an incremented number, usenumber
instead ofnumber
.For
--
, the same is naturally true.