silvertown silvertown - 6 months ago 27
jQuery Question

Bind vertical scroll position to counter

I'm guessing this is really easy but I'm new to jQuery so I'm a little lost.

What’s the best way to animate a number going up relative to a users vertical scroll position? I’m making a div a million pixels long and want a fixed number that counts from 0 to a million. Am I right in saying I'd have to use the .scrollTop() function?

Cheers for any help in advanced!

B

Answer

The following code should help you to get started. If you increase the height of the html tag to 1 million pixel, you'll have a counter with the desired range.

The source code is from this page. I have just created the jsFiddle from it.

$(function() {
    // move the counter with page scroll
    // source from this page http://www.pixelbind.com/make-a-div-stick-when-you-scroll/
    var s = $("#counter");
    var pos = s.position();                   
    $(window).scroll(function() {
        var windowpos = $(window).scrollTop();
        s.html("Distance from top:" + pos.top + "<br />Scroll position: " + windowpos);
        
        if (windowpos >= pos.top) {
            s.addClass("stick");
        } else {
            s.removeClass("stick");
        }
    });
    
});
html {
    /*force to show vert. scrollbar*/
    overflow-y: scroll;
    height: 1000200px;
    background: url("http://placehold.it/1000x500");
}
div#counter {
    padding:20px;
    margin:20px 0;
    background:#AAA;
    width:190px;
}
.stick {
    position:fixed;
    top:0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Dummy text. just to show distance from top calculation.<br/><br/><br/><br/></p>
<div id="counter"></div>