Skip to content

Instantly share code, notes, and snippets.

@LindseyWhitney
Created December 14, 2015 23:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LindseyWhitney/090d6d4a995861d039b7 to your computer and use it in GitHub Desktop.
Save LindseyWhitney/090d6d4a995861d039b7 to your computer and use it in GitHub Desktop.
JavaScript to reveal a fixed header on scroll up only. It is hidden on start, and on scroll down.
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('nav').outerHeight(); // change 'nav' depending on what your containing element is.
var didScroll;
// on scroll, let the interval function know the user has scrolled
$(window).scroll(function(event){
didScroll = true;
});
// run hasScrolled() and reset didScroll status
setInterval(function() {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 250);
function hasScrolled() {
var st = $(this).scrollTop();
if ( Math.abs(lastScrollTop - st) <= delta ) {
return;
}
// If current position > last position AND scrolled past navbar...
if (st > lastScrollTop){
// Scroll Down
$('nav').removeClass('nav-down').addClass('nav-up');
} else {
// Scroll Up
// If did not scroll past the document (possible on mac)...
if(st + $(window).height() < $(document).height()) {
$('nav').removeClass('nav-up').addClass('nav-down');
}
}
lastScrollTop = st;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment