silvertown silvertown - 2 years ago 126
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!


Answer Source

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
    var s = $("#counter");
    var pos = s.position();                   
    $(window).scroll(function() {
        var windowpos = $(window).scrollTop();
        s.html("Distance from top:" + + "<br />Scroll position: " + windowpos);
        if (windowpos >= {
        } else {
html {
    /*force to show vert. scrollbar*/
    overflow-y: scroll;
    height: 1000200px;
    background: url("");
div#counter {
    margin:20px 0;
.stick {
<script src=""></script>
<p>Dummy text. just to show distance from top calculation.<br/><br/><br/><br/></p>
<div id="counter"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download