I'm currently using the code below to hide the header when the user scrolls down, and show it again when they scroll up. It's functioning well, however I would like to append it so that, as well as reappearing on scroll-up, the header also reappears when the user has stopped scrolling for a specified amount of time.
Any help much appreciated.
Current code -
// Hide Header on on scroll down
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('header').outerHeight();
$(window).scroll(function(event){
didScroll = true;
});
setInterval(function() {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 50);
function hasScrolled() {
var st = $(this).scrollTop();
// Make sure they scroll more than delta
if(Math.abs(lastScrollTop - st) <= delta)
return;
// If they scrolled down and are past the navbar, add class .nav-up.
// This is necessary so you never see what is "behind" the navbar.
if (st > lastScrollTop && st > navbarHeight){
// Scroll Down
$('header').removeClass('nav-down').addClass('nav-up');
} else {
// Scroll Up
if(st $(window).height() < $(document).height()) {
$('header').removeClass('nav-up').addClass('nav-down');
}
}
lastScrollTop = st;
}
CodePudding user response:
You could create a function which will check if the user stops scrolling. Then you could handle your logic to display your header in the callback function.
...
// @param {Function} callback The callback function to run after scrolling
// @param {Integer} refresh How long to wait between scroll events [optional]
function scrollStop (callback, refresh = 60) {
// Make sure a valid callback was provided
if (!callback || typeof callback !== 'function') return;
// Setup scrolling variable
let isScrolling;
// Listen for scroll events
window.addEventListener('scroll', function (event) {
// Clear our timeout throughout the scroll
window.clearTimeout(isScrolling);
// Set a timeout to run after scrolling ends
isScrolling = setTimeout(callback, refresh);
}, false);
}
scrollStop(function () {
// logic to display header here
$('header').removeClass('nav-up').addClass('nav-down');
console.log('Scrolling has stopped.');
});