Stick div at top after scrolling example

An example for fiddling.

HTML

<br><br><br>
    
    <div id="container" style="overflow-y: auto; height: 800px;">
        <div id="sticky-anchor"></div>
        <div id="sticky">This will stay at top of page</div>
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
    </div>

CSS

.child {
    height: 200px;
    background: gray;
}

#sticky {
    padding: 0.5ex;
    width: 600px;
    background-color: #333;
    color: #fff;
    font-size: 2em;
    border-radius: 0.5ex;
}
#sticky.stick {
    position: fixed;
    z-index: 10000;
    border-radius: 0 0 0.5em 0.5em;
}
body {
    margin: 1em;
}
p {
    margin: 1em auto;
}

JavaScript

function sticky_relocate() {
    var window_top = $('#container').scrollTop();
    var div_top = $('#sticky-anchor').offset().top;
    if (window_top > div_top) {
        $('#sticky').addClass('stick');
        $('.stick').css('width', $('#sticky').next().css('width'));
    } else {
        $('#sticky').removeClass('stick');
    }
}

$(function () {
    $('#container').scroll(sticky_relocate);
    sticky_relocate();
});