user3742990 user3742990 - 4 months ago 732
HTML Question

Trigger jQuery animated number counter on window scroll

I'm trying to get this jQuery animated counter to trigger as soon as the user scrolls more than 200 pixels down the page:

Original jQuery code from here

$('.Count').each(function () {
var $this = $(this);
jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
duration: 1000,
easing: 'swing',
step: function () {
$this.text(Math.ceil(this.Counter));
}
});
});


I've tried to wrap it in the following jQuery but it doesn't trigger the animation until the end:

$(window).scroll(function() {
if ($(window).scrollTop() > 200) {
$('.Count').each(function () {
var $this = $(this);
jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
duration: 1000,
easing: 'swing',
step: function () {
$this.text(Math.ceil(this.Counter));
}
});
});
}
});


HTML:

<span class="Count">100</span>
<br/>
<span class="Count">200</span>
<br/>
<span class="Count">300</span>


The fiddle from the other post is here

What would be the best way to trigger the jQuery counter as soon as the user scrolls into view or 200 pixels down the page? I've also tried the jQuery Wayfinder but not had any luck with making it work.

Answer

Unbind the scroll handler (with $(window).off("scroll")) before triggering the animation to prevent the animation from restarting if the user continues to scroll.

$(window).scroll(startCounter);
function startCounter() {
    if ($(window).scrollTop() > 200) {
        $(window).off("scroll", startCounter);
        $('.Count').each(function () {
            var $this = $(this);
            jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
                duration: 1000,
                easing: 'swing',
                step: function () {
                    $this.text(Math.ceil(this.Counter));
                }
            });
        });
    }
}
body {
    font-family: sans-serif;
    height: 300vh;
}
.Count {
    position: fixed;
    top: 8px;
    left: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Count">100</div>

Comments