I made a Static website; here is the GitHub link: https://peepsenpai.github.io/ecommerce1/
I wanna show the countdown of the 'counter sec' when its visible on user viewport. my DOM is like this for that particular section:
<section class="counter-sec">
<div class="container">
<div class="row text-center">
<div class="col-md-3 mb-lg-0 mb-md-0 mb-4 mt-2">
<h3>
<span id="count1"></span>+
</h3>
<p>Sellable Items</p>
</div>
<div class="col-md-3 mb-lg-0 mb-md-0 mb-4">
<h3>
<span id="count2"></span>+
</h3>
<p>Total Sells</p>
</div>
<div class="col-md-3 mb-lg-0 mb-md-0 mb-4">
<h3>
<span id="count3"></span>K+
</h3>
<p>Customers</p>
</div>
<div class="col-md-3 mb-lg-0 mb-md-0 mb-4">
<h3>
<span id="count4"></span>+
</h3>
<p>Clients</p>
</div>
</div>
</div>
</section>
And My Logic is this :
document.addEventListener("DOMContentLoaded", () => {
function counter(id, start, end, duration) {
let object = document.getElementById(id),
current = start,
range = end - start,
increment = end > start ? 1 : -1,
step = Math.abs(Math.floor(duration / range)),
timer = setInterval(() => {
current += increment;
object.textContent = current;
if (current == end) {
clearInterval(timer);
}
}, step);
console.log(id);
}
counter("count1", 0, 1509, 3567);
counter("count2", 0, 2000, 3456);
counter("count3", 0, 500, 9567);
counter("count4", 0, 600, 2000);
});
currently the function fires whenever the DOM whole content is fully loaded. for now if I put the section somewhere down in my page , I cant see the countdown from the beginning, cause its already started way before I scroll down to that part. I want to invoke it only when it visible to the user. How can I do that?