Help with my super simple counter

Hello All,

That bit of JavaScript posted below works just fine when counting inside the button container, however I really want to be able to change “data-to=” value inside the heading. How would I accomplish this?

<h2 class="count-number" data-to="1" data-speed="1500"></h2>
<button id="add-one">Add One</button>
var button = document.getElementById("add-one"),
  count = 0;
button.onclick = function() {
  count += 1;
  button.innerHTML = "Add One: " + count;
};

Hi @CooKachoo, first you also need a reference to the .count-number element (you can use querySelector() if it doesn’t have an ID); then you can set its data attribute like so:

var button = document.getElementById('add-one')
var counter = document.querySelector('.count-number')
var count = 0

button.addEventListener('click', function () {
  count += 1
  counter.dataset.to = count
})

(BTW I’d suggest to always use addEventListener() instead of assigning to onclick properties – here’s why.)

1 Like

you should assign a reference to h2 dom, such as document.querySelector('.count-number'), then reset it’s data-to prop’s value.

var button = document.getElementById("add-one"),
  count = 0;
const heading = document.querySelector('.count-number');
button.onclick = function() {
  count += 1;
  button.innerHTML = "Add One: " + count;
  heading.setAttribute("data-to", count);
};

That’s it. May this can help you out.

1 Like

If we’re tossing in ideas, dump the global variable entirely.

button.addEventListener('click', function () {
  counter.dataset.to = parseInt(counter.dataset.to) + 1;
}
2 Likes

Should we protect against no dataset.to value resulting in NaN all the time, by defaulting to zero?

button.addEventListener('click', function () {
  const count = counter.dataset.to || 0;
  counter.dataset.to = parseInt(count) + 1;
});
2 Likes

Wow thanks for all the replies. I’m still at the very beginning of JavaScript studies, and admittedly much of the conversation here is over my head. I tried the scripts offered by @m3g4p0p and @fengxh without much success…

I did create a CodePen project to better help understand what I’m working on.

The data-to attribute is getting updated fine, but this won’t automatically restart that counter animation; it only uses the data attributes for the default options. So you’ll have to invoke it again after clicking the button:

var button = document.getElementById("add-one")
var heading = document.querySelector('.count-number')
var count = 0

button.addEventListener('click', function () {
  count += 1
  button.textContent = 'Add One: ' + count;
  // Pass new options here
  $(heading).countTo({ to: count })
});
1 Like