Here is the code I use to create a "sticky" sidebar. You'll need to modify the IDs to suit your markup.
var sidebarScrollTop = 0;
$(document).ready(function() {
sidebarScrollTop = $("#sidebar").offset();
$(window).scroll(function () {
var docScrollTop = $('body,html').scrollTop();
if(docScrollTop > sidebarScrollTop.top) {
$("#sidebar").css({ position: 'fixed', top: '0px' });
} else {
$("#sidebar").css({ position: 'static' });
}
});
});
$(window).resize(function() {
sidebarScrollTop = $("#sidebar").offset().top;
});
$(document).resize(function() {
sidebarScrollTop = $("#sidebar").offset().top;
});
Basically, all you need to do is change the #sidebar
for the ID of the sidebar container. This code will see if the sidebar element is scrolled past the top of the screen. If it is, it changes it's position to fixed
, and when it returns to being on the page again, the position is returned to static
(default).
The $(document).resize()
and $(window).resize()
functions will make sure the sidebar stays stick at the top of the page when the document/window is resized respectively. The document function will ensure the sidebar works properly even if you have jQuery animations changing the size of elements.
position:fixed
?