I’ve a few divs with empty span in them and these are meant to start counter that would count up to specified number. I grabbed some code (I’m not very good with JS) from the web and made it work for the first div but I don’t know how to loop(?) over their remaining divs.
let counts = setInterval(updated, 100);
let upto = 0;
function updated() {
let count = document.getElementById("counter-1");
count.innerHTML = ++upto;
if (upto === 100) {
clearInterval(counts);
}
}
.various__item--skill-quantity {
color: black;
transition: all 0.5s;
margin: 0 5%;
}
<div class="various__item--skills-quantity" id="counter-1"><span></span></div>
<div class="various__item--skills-quantity" id="counter-2"><span></span></div>
<div class="various__item--skills-quantity" id="counter-3"><span></span></div>
<div class="various__item--skills-quantity" id="counter-14"><span></span></div>
2
Answers
First off, this is THE documentation for js on the web : https://developer.mozilla.org/en-US/docs/Web/JavaScript
I highly recommend bookmarking it and giving it a good read through.
One way that you can go about looping through is to collect / define a NodeList by class name and work your way through that:
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
you can use different methods to loop through this. a basic, but great way to do this is a ‘for…of’ loop https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for…of
when you are looping through, n is your node / element / div
This example works, though it does STOP running when the count reaches 100.
Hope this helps!
Here is a functional approach to this problem.
First, you will need to access all the timers at once. After you have the timer elements, you can initialize them. You can use data attributes to keep track of the state of each timer.
With
Math.sign
, you can determine the direction of the timer.Here is a promise version, that may be easier to follow. Each promise encapsulates the entire logic.