Count when in Viewport

Only starts count when in viewport and drops unnecessary zeros

by Glynne Turner

HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div id="upper-push">
Scroll down
</div>
<div id="numbers">
  <span class="stat">500.500</span>
  <span class="stat">78</span>
</div>
<div id="upper-push">
Scroll down
</div>

CSS

html,
body {
  height:100%;
}

#upper-push {
  height:100%;
  width:100%;
  display:block;
  background:steelblue;
  color:white;
}

JavaScript

// inViewport jQuery plugin
// http://stackoverflow.com/a/26831113/383904
// Based on Fiddle: https://jsfiddle.net/2v3mq3nh/4/
// From this Answer: http://stackoverflow.com/a/36980280
$(function($, win) {
  $.fn.inViewport = function(cb) {
    return this.each(function(i,el){
      function visPx(){
        var H = $(this).height(),
            r = el.getBoundingClientRect(), t=r.top, b=r.bottom;
        return cb.call(el, Math.max(0, t>0? H-t : (b<H?b:H)));  
      } visPx();
      $(win).on("resize scroll", visPx);
    });
  };
}(jQuery, window));
    
jQuery(function($) { // DOM ready and $ in scope

  $(".stat").inViewport(function(px) { // Make use of the `px` argument!!!
    // if element entered V.port ( px>0 ) and
    // if prop initNumAnim flag is not yet set
    //  = Animate numbers
    if(px>0 && !this.initNumAnim) { 
      this.initNumAnim = true; // Set flag to true to prevent re-running the same animation
      $(this).prop('Counter',0).animate({
        Counter: $(this).text()
      }, {
        duration: 1000,
        step: function (now) {
          $(this).text(parseFloat(now.toFixed(4)));
        }
      });         
    }
  });

});