JAVIER MARTIN BALSA
JAVIER MARTIN BALSA

Reputation: 27

Javascript Counters starts on scroll

I need this counter starts on the scroll, not before. Is it possible?

function startCounter(){
    $('.counter').each(function (index) {
        $(this).prop('Counter',0).animate({
            Counter: $(this).text()
        }, {
            duration: 2000,
            easing: 'swing',
            step: function (now) {
                $(this).text(Math.round(now*10)/10);
            }
        });
    });
}   

startCounter();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="counter">92.2</span>

Upvotes: 2

Views: 101

Answers (2)

caramba
caramba

Reputation: 22480

Call the function from inside the scroll event listener

window.addEventListener('scroll', function(event) {
  // you could do startCounter(); here
  // maybe you want to check the event or the scroll position (window.scrollY)
  // maybe you pass the event to the startCounter(event) function
  console.log('scroll is happening, window.scroll position is:', window.scrollY)
});
<div style="height:10000px;width:200px;background-color:orange">just a big div to let the scroll appear</div>

For more information about the scroll event see: https://developer.mozilla.org/en-US/docs/Web/API/Document/scroll_event

Upvotes: 3

Akash Srivastav
Akash Srivastav

Reputation: 766

This will do it for you.

window.addEventListener('scroll', function(e) {
    startCounter();
});

Upvotes: 1

Related Questions