Skip to content

Instantly share code, notes, and snippets.

@gmarokov
Last active October 22, 2019 06:50
Show Gist options
  • Save gmarokov/f52a93cadfec0b840357fd9b6720011b to your computer and use it in GitHub Desktop.
Save gmarokov/f52a93cadfec0b840357fd9b6720011b to your computer and use it in GitHub Desktop.
JQuery sticky sidebar
var stickySidebar = $('.sticky');
if (stickySidebar.length > 0) {
var stickyHeight = stickySidebar.height(),
sidebarTop = stickySidebar.offset().top;
}
// on scroll move the sidebar
$(window).scroll(function () {
if (stickySidebar.length > 0) {
var scrollTop = $(window).scrollTop();
if (sidebarTop < scrollTop) {
stickySidebar.css('top', scrollTop - sidebarTop);
// stop the sticky sidebar at the footer to avoid overlapping
var sidebarBottom = stickySidebar.offset().top + stickyHeight,
stickyStop = $('.main-content').offset().top + $('.main-content').height();
if (stickyStop < sidebarBottom) {
var stopPosition = $('.main-content').height() - stickyHeight;
stickySidebar.css('top', stopPosition);
}
}
else {
stickySidebar.css('top', '0');
}
}
});
$(window).resize(function () {
if (stickySidebar.length > 0) {
stickyHeight = stickySidebar.height();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment