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?
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.)
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 })
});