0

I just wanna run a function when my height of my div reaches the bottom of the page on scroll? Is their any way to do that using JavaScript?

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Sahad
  • 1

1 Answers1

0

The most contemporary JS solution is to use an intersection observer. (MDN). It is less resource intensive than older solutions that listen to the scroll event. With the intersection observer you can decide exactly where you want the function to trigger and you can reuse it like this example shows:

class CountUp {
  constructor(triggerEl, counterEl) {
  const counter = document.querySelector(counterEl)
  const trigger = document.querySelector(triggerEl)
  let num = 0

  const countUp = () => {
    if (num <= counter.dataset.stop)
      ++num
      counter.textContent = num
  }
  
  const observer = new IntersectionObserver((el) => {
    if (el[0].isIntersecting) {
      const interval = setInterval(() => {
        (num < counter.dataset.stop) ? countUp() : clearInterval(interval)
      }, counter.dataset.speed)
    }
  }, { threshold: [0] })

  observer.observe(trigger)
  }
}

// Initialize any number of counters:
new CountUp('#start1', '#counter1')
new CountUp('#start2', '#counter2')
p {
  font-weight: bold;
  text-align: center;
  margin-top: 5%;
  font-size: 2rem;
  color: green;
}

.start-counter {
  text-align: center;
  padding: 0 0 5rem;
}

.counter {
  text-align: center;
  /* transition: .1s ease; */
  font-size: 14rem;
  color: red;
  font-weight: bold;
  font-family: sans-serif;
  padding: 0 0 30rem;
}
<p>Scroll down &darr;</p>
<div style="height:100vh;"></div>
<div id="start1" class="start-counter">Counter starts counting here!</div>
  <div id="counter1" class="counter" data-stop="199" data-speed="20">0</div>

<p>Scroll down &darr;</p>
<div style="height:100vh;"></div>
<div id="start2" class="start-counter">Counter starts counting here!</div>
<div id="counter2" class="counter" data-stop="300" data-speed="20">0</div>
anatolhiman
  • 1,762
  • 2
  • 14
  • 23