Skip to content
Advertisement

how to increase counter from 1, 2, to 3, with one click? [closed]

i have some code but i am doing something wrong, how can i increment the value smoothly to 3? At the end when the counter is 3 I should see the initial value “click me: 0”

document.querySelector('.btn-counter').addEventListener('click', (e) => {
  const btn = e.target;
  let curr = (+btn.dataset.clicks)
  btn.dataset.clicks = ++curr % 4;

  btn.innerHTML = 'click me: ' + btn.dataset.clicks;
});
.btn-counter {
  cursor: pointer;
}
<div class="btn-counter" id="clicks" data-clicks="0">clikc me: 0</div>

Advertisement

Answer

I think this is what you’re trying to do – note the addition of data-clicks="0" on the element itself.

document.querySelector('.btn-counter').addEventListener('click', (e) => {
  const btn = e.target;
  let curr = (+btn.dataset.clicks)
  btn.dataset.clicks = ++curr % 4;

  btn.innerHTML = 'click me: ' + btn.dataset.clicks;
});
.btn-counter {
  cursor: pointer;
}
<div class="btn-counter" id="clicks" data-clicks="0">click me: 0</div>

Turns out thats not what you were after, but instead to animate the count and return to 0.

document.querySelector('.btn-counter').addEventListener('click', (e) => {
  let curr = 0;
  const btn = e.target;
  const delay = 1000;
  
  const increment = () => {
    curr++;
    btn.innerHTML = curr;
    if(curr <4)
      setTimeout(increment,delay);
    else {
      curr = 0
      btn.innerHTML = "click me: 0"
    }
  }
  
  setTimeout(increment,delay);
  
});
.btn-counter {
  cursor: pointer;
}
<div class="btn-counter" id="clicks">click me: 0</div>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement