Skip to content

Instantly share code, notes, and snippets.

@dmtintner
Created February 14, 2013 16:00
Show Gist options
  • Save dmtintner/4953754 to your computer and use it in GitHub Desktop.
Save dmtintner/4953754 to your computer and use it in GitHub Desktop.
sidebar becomes fixed position after scroll x amount
$(function(){
if (isMobile())
return;
// Back To Top Button and fixed sidebar
var backToTopButton = $('#back-to-top');
var sidebar = $('#sidebar');
var footer = $('#footer');
var headerOuterHeight = $('#header').outerHeight();
var refreshSidebarTop = function(sidebar, headerOuterHeight) {
return sidebar.offset().top - headerOuterHeight;
}
var absoluteSidebarTop = refreshSidebarTop(sidebar, headerOuterHeight);
$(window)
.scroll(function(){
if ($(this).scrollTop() >= absoluteSidebarTop) {
backToTopButton.addClass('show');
sidebar.addClass('fixed');
footer.addClass('fixed').css({'top': sidebar.outerHeight()+headerOuterHeight});
} else {
sidebar.removeClass('fixed');
footer.removeClass('fixed').css({'top': sidebar.outerHeight()+$('#headline').outerHeight(true)});
backToTopButton.removeClass('show');
}
})
.on('sidebarHeightChanged', function(){
absoluteSidebarTop = refreshSidebarTop($('#sidebar'), $('#header').outerHeight());
footer.removeClass('fixed').css({'top': sidebar.outerHeight()+$('#headline').outerHeight(true)});
});
backToTopButton.click(function(){
$('body').animate({ scrollTop: 0 }, 'slow');
return false;
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment