Liz
Liz

Reputation: 1048

How to trigger jQuery counter when element is in window?

I have this jQuery code that triggers a counter from 0 to 1750. But, this counter is at the bottom of my page, and if you don't scroll to it quickly enough you miss the counter animation. Is there a way to trigger this to run only once you've hit the element in the window?

// Counter
$(document).ready(function() {
    $('.count').each(function() {
        $(this).prop('Counter', 0).animate({
            Counter: $(this).text()
        }, {
            duration: 12000,
            easing: 'swing',
            step: function(now) {
                $(this).text(Math.ceil(now));
            }
        });
    });
});

Upvotes: 1

Views: 934

Answers (1)

Orlando Charles
Orlando Charles

Reputation: 165

Try something like this, check your window top position and if is higher or equal of your target element and less the window height, then do your count animation.

HTML

<div class="wrapper-count">
  <ul>
    <li class="count">0</li>
    <li class="count">0</li>
    <li class="count">0</li>
  </ul>
</div>

JS

$(document).ready(function(){
  $(function(){
    $(window).on("scroll", function(){
      var win_height = $(this).height();
      var win_pos    = $(this).scrollTop();
      var top_pos    = $(".wrapper-count").position().top;

      if(win_pos >= top_pos - win_height){
        // here goes your count logic
      }
    });
  });
});

Upvotes: 1

Related Questions