Stick div at top after scrolling example
An example for fiddling.
HTML
<br><br><br>
<div id="container" style="overflow-y: auto; height: 800px; position: relative;">
<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;
background-color: #333;
color: #fff;
font-size: 2em;
border-radius: 0.5ex;
}
#sticky.stick {
position: absolute;
top: 0;
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;
$('.stick').css('width', $('#sticky').next().css('width'));
if (window_top > div_top) {
$('#sticky-anchor').height($("#sticky").outerHeight());
$('#sticky').addClass('stick');
$("#sticky").css("top", (window_top) + "px");
} else {
$('#sticky').removeClass('stick');
$('#sticky-anchor').height(0);
}
}
$(function () {
$('#container').scroll(sticky_relocate);
sticky_relocate();
});