* Scroll with sticky div + scroll position

by ian_smithz

HTML

<p>
    <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 () {

    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");
        }
    });

});