CharlyAnderson
CharlyAnderson

Reputation: 737

Counter not reaching value

I am using the following code for counters. I've noticed that the counter doesn't always reach the higher values (specifically 5500) - adjusting the speed doesn't to fix the problem. Does anyone know what the problem could be?

startCounter();

function startCounter() {
  var hT = $('.value').offset().top,
    hH = $('.value').outerHeight(),
    wH = $(window).height();
  if ($(window).scrollTop() > hT + hH - wH) {
    $(window).off("scroll", startCounter);
    $('.value').each(function() {
      var $this = $(this);
      jQuery({
        Counter: 0
      }).animate({
        Counter: $this.text()
      }, {
        duration: 3500,
        easing: 'linear',
        step: function() {
          $this.text(Math.ceil(this.Counter) + '');
        }
      });
    });
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="value">5500</span>

Upvotes: 0

Views: 88

Answers (1)

Salketer
Salketer

Reputation: 15711

I've added the complete callback, exactly the same as step callback. The thing about step is that it is executed to manipulate the tween, this means it is not called at the end of the animate (aka when you reach the wanted value)

startCounter();

function startCounter() {
  var hT = $('.value').offset().top,
    hH = $('.value').outerHeight(),
    wH = $(window).height();
  if ($(window).scrollTop() > hT + hH - wH) {
    $(window).off("scroll", startCounter);
    $('.value').each(function() {
      var $this = $(this);
      jQuery({
        Counter: 0
      }).animate({
        Counter: $this.text()
      }, {
        duration: 3500,
        easing: 'linear',
        step: function() {
          $this.text(Math.ceil(this.Counter) + '');
        },
        complete(){
          $this.text(Math.ceil(this.Counter) + '');
        }
      });
    });
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="value">5500</span>

Upvotes: 3

Related Questions