'How to make elements count differently on Counter with javascript
I have a counter which I made with Javascript, I want to add a function or anything else to delay the count at some elements so that they count on with the same speed. here is an example on this website https://www.ifunds-germany.de/ => standorte starts to count late.
let counter = document.getElementById('counter');
window.addEventListener('scroll', () => {
// This is then function used to detect if the element is scrolled into view
function isScrolledIntoView(el) {
var rect = el.getBoundingClientRect();
var elemTop = rect.top;
var elemBottom = rect.bottom;
// Only completely visible elements return true:
var isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
// Partially visible elements return true:
//isVisible = elemTop < window.innerHeight && elemBottom >= 0;
return isVisible;
}
// This is where we use the function to detect if ".box2" is scrolled into view, and when it is add the class ".animated" to the <p> child element
if (isScrolledIntoView(counter)) {
const counters = document.querySelectorAll(".counter");
const speed = 200;
counters.forEach(counter => {
const updateCount = () => {
const target = +counter.getAttribute('data-target');
const count = +counter.innerText;
const inc = target / speed;
if (count < target) {
counter.innerText = Math.ceil(count + inc);
setTimeout(updateCount, 1);
} else {
count.innerText = target;
}
}
updateCount();
});
}
});
<div id="counter">
<div class="g-grid counters" style="justify-content: space-between;">
<div class="g-block size-20 g-infolist-item-white-background">
<i class="fa-solid fa-calendar-plus fa-5x"></i>
<div class="counter" data-target="15">0</div>
<h2 class="g-main-feature-title">Jahre Erfahrung</h2>
</div>
<div class="g-block size-20 g-infolist-item-white-background">
<i class="fa-solid fa-list-check fa-5x"></i>
<div class="counter" data-target="150">0</div>
<h2 class="g-main-feature-title">erfolgreiche Projekte</h2>
</div>
<div class="g-block size-20 g-infolist-item-white-background">
<i class="fa-solid fa-code fa-5x"></i>
<div class="counter" data-target="1000000">0</div>
<h2 class="g-main-feature-title">Zeilen Code</h2>
</div>
<div class="g-block size-20 g-infolist-item-white-background">
<i class="fa-solid fa-mug-saucer fa-5x"></i>
<div class="counter" data-target="324000">0</div>
<h2 class="g-main-feature-title">Tassen Kaffee</h2>
</div>
</div>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
