Carl
Carl

Reputation: 357

How can i activate a function when i scroll to div?

So I have a counter, and when I scroll to div, it should start counting, but it starts counting right as the whole page loads.

Counters on a website: enter image description here

Html code of counters:

<section class="counters">
  <div class="container2">
    <div>
      <i class="far fa-smile"></i>
      <div class="counter" data-target="232">0</div>
      <p>Happy Clients consequuntur quae</p>
    </div>
    <div>
      <i class="fas fa-book"></i>
      <div class="counter" data-target="521">0</div>
      <p>Projects adipisci atque cum quia aut</p>
    </div>
    <div>
      <i class="fas fa-headphones"></i>
      <div class="counter" data-target="1463">0</div>
      <p>Hours Of Support aut commodi quaerat</p>
    </div>
    <div>
      <i class="fas fa-user-friends"></i>
      <div class="counter" data-target="15">0 </div>
      <p>Hard Workers rerum asperiores dolor</p>
    </div>
  </div>
</section>

Code of the function:

$('.counters counters2').waypoint(function() {
    const counters = document.querySelectorAll('.counter');
    const speed = 50; // The lower the slower

    counters.forEach(counter => {
        const updateCount = () => {
            const target = +counter.getAttribute('data-target');
            const count = +counter.innerText;

            // Lower inc to slow and higher to slow
            const inc = target / speed;

            // console.log(inc);
            // console.log(count);

            // Check if target is reached
            if (count < target) {
                // Add inc to count and output in counter
                counter.innerText = count + 3;
                // Call function every ms
                setTimeout(updateCount, 1);
            } else {
                counter.innerText = target;
            }
        };

        updateCount();
    });
});  

}

So I used waypoint from jquery to activate the function when I scroll to div, but for some reason, the function activates when the page is loaded, without scrolling to the specific div.

Upvotes: 1

Views: 1390

Answers (3)

Ziglewis
Ziglewis

Reputation: 13

Sorry, I may not be able to read your code and tell you why it's not working but I also had a need for such a solution, after much going around this worked for me and I have taken the time to explain it. Perhaps you can go through and modify the function to do whatever you desire. I am very young in Javascript so my solution may not be the best, but somehow it works. I just hope you find something meaningful in it.

// Get the div element with the id "monkey".
 const monkey = document.getElementById('monkey');


  checkVisibility = () => {

 // Check if the div element is scrolled into view.
 if (monkey.getBoundingClientRect().top < window.innerHeight/2 ) {

   // Change the background color to red.
   monkey.style.backgroundColor = 'red';
   
   monkey.innerText = "I made it at last hurrayyyyy!!! " + window.innerHeight
   
   
   //If you want this to happen only once then you can add line 20, if not don't remove the eventlistiner as I did in line 20(I mean delete line 20)
   window.removeEventListener('scroll', checkVisibility )
   
 }
}


// Set a listener for the "scroll" event below the function.
window.addEventListener('scroll', checkVisibility );
 EXPLANATION TO CODE

/*
COMMENTS
see JAVASCRIPT line 11: I did 
window.innerHeight/2  ...divided by two will mean that when the monkey div gets to half of the screen, the function is fired. you can mathematically twerk that to what you want. 

if you remove the divide by two entirely, by that I mean to change the code at line 11 as 
if (monkey.getBoundingClientRect().top < window.innerHeight) {

immediately the monkey div appears on the screen the function is fired.

CAUTION: DO NOT PLACE LINE 27 ABOVE LINE 8 AS YOU WILL BE SETTING THE EVENT LISTENER AHEAD OF THE FUNCTION AND IT MAY NOT WORK. AT LEAST WHEN I TRIED IT OUT, THAT WAS WHAT I FOUND.

*/
<!DOCTYPE html>
<html lang="en">
<head>
    <title>ZigLewis solution to making a function run when an element gets to a particular screen position
    </title>
</head>

<body>




 <p> Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quidem doloremque molestiae delectus asperiores, eaque totam? Dicta deleniti repelr vel duptates mollitia rem doloremque excepturi reprehenderit fugit exercitationem incidunt. Non deleniti beatae fuga fugit culpa aliquam fugiat error .</p>
 
 <p> Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quidem doloremque molestiae delectus asperiores, eaque totam? Dicta deleniti repe </p>
<p> SCROLL UP SLOWLY TILL YOU CANT SEE ME! </p>
<br>
<hr>
 

<div id = "monkey"> KEEP YOUR EYES HERE ON THE MONKEY </div>
<hr>
<br>
<br>

        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quidem doloremque molestiae delectus asperiores, eaque totam? Dicta deleniti repelr vel duptates mollitia rem doloremque excepturi reprehenderit fugit exercitationem incidunt. Non deleniti beatae fuga fugit culpa aliquam fugiat error provident facere quo soluta porro accusamus qui sed assumenda, alias excepturi ratione minus voluptates vel aspernatur cum doloribus sapiente. Libero, consequatur quam at quos quae rem.
 <p> Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quidem doloremque molestiae delectus asperiores, eaque totam? Dicta deleniti repelr vel duptates mollitia rem doloremque excepturi reprehenderit fugit exercitationem incidunt. Non deleniti beatae fuga fugit </p>
 


 <p> Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quidem doloremque molestiae delectus asperiores, eaque totam? Dicta deleniti repelr vel duptates mollitia rem doloremque excepturi reprehenderit fugit exercitationem incidunt. Non deleniti beatae fuga fugit </p>
 
  <p> Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quidem doloremque molestiae delectus asperiores, eaque totam? Dicta deleniti repelr vel duptates mollitia rem doloremque excepturi reprehenderit fugit exercitationem incidunt. Non deleniti beatae fuga fugit </p>

 </body>
</html>

Upvotes: 0

Zouhair Dre
Zouhair Dre

Reputation: 628

Here is a simple example using onscroll and offsetTop.

<!DOCTYPE html>
<html>
<head>
<style>
#myDiv{
margin-top:1600px;
}
</style>
</head>
<body style="height:1500px">
  <div id="myDiv" >
      <p>Scroll down to this div</p>
  </div>
<script>
  window.onscroll = function() {myFunction()};

  function myFunction() {
      var testDivFromTop = document.getElementById("myDiv").offsetTop;
      var pageHeight =  window.innerHeight;
      if (document.body.scrollTop > testDivFromTop - pageHeight || document.documentElement.scrollTop > testDivFromTop - pageHeight ) {
              alert(1);
      }
  }
</script>

</body>
</html>

Upvotes: 2

Mohammed Naguib
Mohammed Naguib

Reputation: 594

The way I would do it was simply use onscroll event . see the link https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onscroll

Upvotes: 0

Related Questions