Skip to content

Instantly share code, notes, and snippets.

@simeonpashley
Created July 16, 2018 11:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simeonpashley/0e5f9832f65c4eec21d46e6231f33809 to your computer and use it in GitHub Desktop.
Save simeonpashley/0e5f9832f65c4eec21d46e6231f33809 to your computer and use it in GitHub Desktop.
Sticky header
//sticky
$(function() {
// Hide Header on on scroll down
var didScroll = false;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('.c-header').outerHeight() + 30;
if ($(window).scrollTop() == 0) {
$('.c-header').addClass('js-at-top');
} else {
$('.c-header').removeClass('js-at-top');
}
$(window).scroll(function(event) {
didScroll = true;
});
setInterval(function() {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 25);
function hasScrolled() {
var scrollLoc = $(this).scrollTop();
// Make sure they scroll more than delta
if (Math.abs(lastScrollTop - scrollLoc) <= delta)
return;
// If they scrolled down and are past the navbar, add class .js-scroll-up.
// This is necessary so you never see what is "behind" the navbar.
if (scrollLoc > lastScrollTop && scrollLoc > navbarHeight) {
// Scroll Down
$('.c-header, .c-toc').removeClass('js-scroll-down').addClass('js-scroll-up');
} else {
// Scroll Up
if (scrollLoc + $(window).height() < $(document).height()) {
$('.c-header, .c-toc').removeClass('js-scroll-up').addClass('js-scroll-down');
}
}
if (scrollLoc == 0) {
$('.c-header').addClass('js-at-top');
} else {
$('.c-header').removeClass('js-at-top');
}
lastScrollTop = scrollLoc;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment