My page contains a counter and I want to add a method that makes the counter start when a certain height has been reached. I've calculated that I want the counter to start at the height of 324px, but since I have very little experience with JavaScript I'm not sure what am i looking for. Can someone help me?
Here's my current code:
const counters = document.querySelectorAll('.counter');
const speed = 2000;
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);
requestAnimationFrame(updateCount, 1);
} else {
count.innerText = target;
}
}
updateCount();
});
<div class="container-b">
<div class="container">
<div class="row">
<div class="counters">
<div class="card-image" id="purple-b">
<i class="fas fa-users"></i>
<div class="counter" data-target="231">0</div>
<p class="card-b-text">Happy Users</p>
</div>
<div class="card-image" id="green-b">
<i class="fas fa-code"></i>
<div class="counter" data-target="385">0</div>
<p class="card-b-text">Issues Solved</p>
</div>
<div class="card-image" id="red-b">
<i class="fas fa-cog"></i>
<div class="counter" data-target="159">0</div>
<p class="card-b-text">Good Reviews</p>
</div>
<div class="card-image" id="orange-b">
<i class="fas fa-comments"></i>
<div class="counter" data-target="127">0</div>
<p class="card-b-text">Case Studies</p>
</div>
<div class="card-image" id="blue-b">
<i class="fas fa-rocket"></i>
<div class="counter" data-target="211">0</div>
<p class="card-b-text">Orders Received</p>
<p></p>
</div>
</div>
</div>
</div>
</div>
I don't know if this is what you're looking for or not. If it's wrong you can describe it more, because I do not quite understand it.
Let's say I have a page with 3000px CSS:
.counter{
height: 3000px;
}
And I want whenever I scroll pass the 324px, it'll do something for you
const counters = document.querySelectorAll('.counter');
window.onscroll=function(){
if(scrollY >= 324){
console.log("Do your start count things or something in here")
}
}
I will do that this way :
use the same requestAnimationFrame()
for both elements, and stop it when there is none to update
const
speed = 2000
, counters = [...document.querySelectorAll('.counter')]
.map(el=>(
{ el
, target : +el.dataset.target
, inc : (el.dataset.target / speed)
, count : parseInt(el.textContent)
}))
;
requestAnimationFrame(updateCount)
function updateCount()
{
let elmsRun = counters.length
counters.forEach(({ el, target, inc, count}, i) =>
{
el.textContent = counters[i].count
= (count < target) ? Math.ceil(count+inc) : target
if (counters[i].count === target) --elmsRun
})
if (elmsRun) requestAnimationFrame(updateCount)
}