Scroll with sticky div + scroll position

by awolf2904

HTML

<p>Dummy text. just to show distance from top calculation.
    <br/>
    <br/>
    <br/>
    <br/>
</p>
<div id="counter"></div>

CSS

html {
    /*force to show vert. scrollbar*/
    overflow-y: scroll;
    height: 1000310px;
    background: url("http://placehold.it/1000x500");
}
div#counter {
    padding:20px;
    margin:20px 0;
    background:#AAA;
    width:190px;
}
.stick {
    position:fixed;
    top:0px;
}

JavaScript

$(function () {
    // move the counter with page scroll
    // source from this page http://www.pixelbind.com/make-a-div-stick-when-you-scroll/
    var counter = 0;
    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");
        }
    });

});