One issue with the code snippet provided is that the Counters do not stop at the same time. Is there a way to adjust the duration of the Counters? I've heard that the animate function in JQuery can be used to adjust the duration, but I'm curious about integrating that with Intersection Observer to ensure that animated numbers run only when they become visible.
const counterElements = document.querySelectorAll(".count");
// Counters
function counter(target, start, stop) {
target.innerText = 0.1;
const counterInterval = setInterval(() => {
start += 0.1;
const valueConverted = (Math.round(start * 100) / 100).toFixed(1);
target.innerText = valueConverted;
if (valueConverted == stop) {
clearInterval(counterInterval);
}
}, 30);
}
function obCallBack(entries) {
entries.forEach((entry) => {
const { target } = entry;
const stopValue = target.innerText;
const startValue = 0;
if (!entry.isIntersecting) return;
counter(target, startValue, stopValue);
counterObserver.unobserve(target);
});
}
const counterObserver = new IntersectionObserver(obCallBack, { threshold: 1 });
counterElements.forEach((counterElem) => counterObserver.observe(counterElem));
.emptyspace{
height:400px;
}
<div class="emptyspace"></div>
<p class="count">5.2</p>
<p class="count">50.9</p>
</div>