JavaScript: increment and decrement functions
P粉761718546
P粉761718546 2024-01-29 09:53:20
0
1
490

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>

P粉761718546
P粉761718546

reply all(1)
P粉759451255

Use number When incrementing the number variable, this statement returns the value before the increment. If you want to get an incremented number, use number instead of number .

For --, the same is naturally true.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template