How to activate counter with a particular scroll

Asked

Viewed 344 times

0

I have the following problem, I need to activate a counter when the user scrolls to the div where the numbers are, but in my code the counter works and then it seems to activate the function again, I tried to use a preventDefault() within the complete but he returns to me Undefined.

Below is an example of my code:

function ativaContador(e){
$('.contador').each(function() {
            $(this).prop('Counter', 0).animate({
                Counter: $(this).text()
            }, {
                duration: 4000,
                easing: 'swing',
                step: function(now) {
                    $(this).text(Math.ceil(now)+'%');
                },
              complete: function(){
            
              },
            });
            
        });
  }

$(window).scroll(function(e) {
  var alturaBody = $(window).height();
  var distanciaElemento = $('.contador').offset().top;
  var posicaoScroll = $(this).scrollTop();
  var alturaElemento = $('.contador').outerHeight();
  
  if (posicaoScroll > (distanciaElemento+alturaElemento-alturaBody)){
    ativaContador();
   } 
});
.bloco{
  height:2000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bloco"></div>
<div class="contador">100</div>

1 answer

0

You are using an animation, and it repeats itself. To stop the repetition you need to use the method stop() when the animation is complete. The first parameter says to clear the Queue of animation, the second says skip to the end animation, which is optional, and the animation is already at the end.

See more: https://api.jquery.com/stop/

function ativaContador(e){
$('.contador').each(function() {
            $(this).prop('Counter', 0).animate({
                Counter: $(this).text()
            }, {
                duration: 4000,
                easing: 'swing',
                step: function(now) {
             
                    $(this).text(Math.ceil(now)+'%');
                },
              complete: function(){
            $(this).stop(true,true)
              },
            });
            
        });
  }

$(window).scroll(function(e) {
  var alturaBody = $(window).height();
  var distanciaElemento = $('.contador').offset().top;
  var posicaoScroll = $(this).scrollTop();
  var alturaElemento = $('.contador').outerHeight();
  
  if (posicaoScroll > (distanciaElemento+alturaElemento-alturaBody)){
    ativaContador();
   } 
});
.bloco{
  height:2000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bloco"></div>
<div class="contador">100</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.