简体   繁体   中英

jQuery - Animate numbers when appears in viewport

I'm currently trying to animate some numbers when the user scroll and the DIV appears in the viewport. Like that: http://www.dimfolio.fr/

On the example it looks to be CSS3, for some reasons I'd prefer to use jQuery.

Currently, I use " animateNumber " plugin and this function to check if the div appears in the viewport:

$.fn.is_on_screen = function(){

var win = $(window);

var viewport = {
    top : win.scrollTop(),
    left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();

var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();

return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));

};

Here is my code:

JS:

function animate_stats() {
  $('.stats_number').each(function() {
     if(!$(this).hasClass("numbered")) {
        var thisnumber = $(this).attr('title');
        $(this).animateNumber({ number: thisnumber }, 3000, function() {
            $(this).addClass('numbered');
        });
     }
  });
};

if( $('#statistics').is_on_screen() ) {
  animate_stats();
}

$(window).scroll(function(){
  if( $('#statistics').is_on_screen() ) {
     animate_stats();
  }
});

HTML:

<a href="#" class="stat">
   <div class="stats_number" title="79">0</div>
   <br />
   My title
</a>

The problem is that the number animation repeats and repeats again when the div appears. Of course I'd like the animation to run only once.

I suppose that the issue comes from my utilisation of "each" function but note sure.

Anyone can help? Thank you very much!

After the animation is run, remove the listener.

$(window).on('scroll.animateStats', function(){
  if( $('#statistics').is_on_screen() ) {
     animate_stats();
     $(window).off('scroll.animateStats');
  }
});

I namespaced the scroll event so that when we remove it we're only removing this event handler, and not all scroll handlers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM