Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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:20px0;
    background:#AAA;
    width:190px;
}
.stick {
    position:fixed;
    top:0px;
}
<scriptsrc="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><divid="counter"></div>

Post a Comment for "Bind Vertical Scroll Position To Counter"