Skip to content

Instantly share code, notes, and snippets.

@ricardobrg
Last active October 29, 2018 08:50
Show Gist options
  • Save ricardobrg/dc2aaad5878a6e7f5d0ea9319b896fb0 to your computer and use it in GitHub Desktop.
Save ricardobrg/dc2aaad5878a6e7f5d0ea9319b896fb0 to your computer and use it in GitHub Desktop.
fixed sidebar with variable height
var fixed = false;
var sidebarTop = jQuery('#secondary').offset().top;
var sidebarHeight = jQuery('#secondary').height();
var windowHeight = jQuery(window).height();
var leftHeight = jQuery('.left-content-area').height();
if (windowHeight < sidebarHeight){
startPosition = sidebarTop + sidebarHeight - windowHeight;
fixPosition = windowHeight - sidebarHeight;
endPosition = leftHeight + sidebarTop - windowHeight;
}else{
fixPosition = 0;
startPosition = sidebarTop + sidebarHeight;
endPosition = sidebarTop;
}
jQuery(window).scroll(function() {
var currentScroll = jQuery(window).scrollTop();
if (!fixed){
if (currentScroll >= startPosition){
fixed = true;
jQuery('#secondary').css({position:'fixed',top:fixPosition});
}
}else{
if (currentScroll <= startPosition){
fixed = false;
jQuery('#secondary').css({position:'relative',top:0});
}else if (currentScroll >= endPosition){
jQuery('#secondary').css({position:'relative',top: leftHeight - sidebarHeight });
}else if (currentScroll <= endPosition){
jQuery('#secondary').css({position:'fixed',top:fixPosition});
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment