I am using the following code on my website. I have the section positioned farther down on the page so that it is not immediately visible. What is happening now is that by the time the visitor to the website scrolls to this section the numbers have already counted up and I would like it to animate at the time the section comes into view. How can I make the snippet activate only when this section is visible in the browser window as the visitor scrolls?
$('.counter').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({
countNum: $this.text()
}).animate({
countNum: countTo
},
{
duration: 2000,
easing: 'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
//alert('finished');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="counter" data-count="150">0</div>
<div class="counter" data-count="85">0</div>
<div class="counter" data-count="2200">0</div>