Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

jquery - Animate counter when in viewport

I have a counter which animates to a final number which is defined in the HTML. However I would like this animation to happen once it's in the viewport.

I have a fiddle here which shows how scrolling seems to effect the counter number.

$(document).ready(function() {
      $(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));

      $(".fig-number").inViewport(function(px) {
        $(this).each(function() {
          $(this).prop('Counter', 0).animate({
            Counter: $(this).text()
          }, {
            duration: 1000,

            step: function(now) {
              $(this).text(Math.ceil(now));
            }
          });
        });
      });
    });

I've tried multiple things but I cant seem to achieve what I'm after.

$(document).ready(function() {
  $(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));

  $(".fig-number").inViewport(function(px) {
    $(this).each(function() {
      $(this).prop('Counter', 0).animate({
        Counter: $(this).text()
      }, {
        duration: 1000,

        step: function(now) {
          $(this).text(Math.ceil(now));
        }
      });
    });
  });
});
html,
body {
  height: 100%;
}
#upper-push {
  height: 100%;
  width: 100%;
  display: block;
  background: red;
  color: white;
}
<div id="upper-push">
  Scroll down
</div>
<div id="numbers">
  <span class="fig-number">25</span>
  <span class="fig-number">78</span>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The .inViewport() plugin triggers a callback on every scroll event.
It's by design. (Helps to keep the source of a plugin in code! ;) )

On the "plugin page" you can see how to use it:

$("selector").inViewport(function(px) {
  console.log( px ); // `px` represents the amount of visible height
  if(px){
    // do this if element enters the viewport // px > 0
  }else{
    // do that if element exits  the viewport // px = 0
  }
}); // Here you can chain other jQuery methods to your selector 

that means:

  1. You have to listen for the px argument is greater than 0 (element is in viewport)
  2. To prevent chaining additional animations creating buildups, you should use a flag variable
  3. (The $(this).each() inside the callback is not needed. The plugin already operates over a collection of elements.)

Edited jsFiddle demo

jQuery(function($) { // DOM ready and $ in scope

  $(".fig-number").inViewport(function(px) {
    // if px>0 (entered V.port) 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
      // <<< DO SOME COOL STUFF HERE! 
    }
  });

});

Snippet example:

// inViewport jQuery plugin
// https://stackoverflow.com/a/26831113/383904
$(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

  $(".fig-number").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(Math.ceil(now));
        }
      });         
    }
  });

});
html,
body {
  height:100%;
}

#upper-push {
  height:100%;
  width:100%;
  display:block;
  background:red;
  color:white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="upper-push">
  Scroll down
</div>
<div id="numbers">
  <span class="fig-number">25</span>
  <span class="fig-number">78</span>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...