Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

147
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda