Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
How to fire a particular function to a particular section(in DOM) when it visible in the viewport?

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!