How to activate counter with a given scroll

0

I have the following problem, I need to activate a counter when the scroll scroller to the div where the numbers are, but in my code the counter works and then it seems that it activates the function again, I tried using a preventDefault () within complete but it returns me undefined .

Here 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><divclass="bloco"></div>
<div class="contador">100</div>
    
asked by anonymous 16.03.2017 / 16:09

1 answer

0

You are using an animation, and it repeats itself. To stop the replay, you must use the stop() method when the animation is complete. The first parameter says to clear the Queue of the animation, the second says to skip to the end of the animation, which is optional, / p>

See more: link

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><divclass="bloco"></div>
<div class="contador">100</div>
    
17.03.2017 / 14:55