[Hide Header on Scroll] Hide the header when scrolling #javascript
States: 1 - HEADER when user is at top of page 2 - .header-hide when user scrolls down 3 - .header-show when user scrolls up
1/26/22 - added a vanilla js equivalent. Credit: https://webdesign.tutsplus.com/tutorials/how-to-hide-reveal-a-sticky-header-on-scroll-with-javascript--cms-33756
jQ171(document).ready(function ($) {
/* ==========================================================================
Hide Header OnScroll
========================================================================== */
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var headerHeight = $('.scroll-header').outerHeight();
$(window).scroll(function (event) {
didScroll = true;
});
setInterval(function () {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 120);
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 > 120) {
// Scroll Down
$('.scroll-header').removeClass('header-show').addClass('header-hide');
// when user gets to ~XXX pixels from the top of page, remove classes
} else if (window.scrollY <= 120) {
$("header").removeClass("header-show");
$("header").removeClass("header-hide");
} else {
// Scroll Up
if (st + $(window).height() < $(document).height()) {
$('.scroll-header').removeClass('header-hide').addClass('header-show');
}
}
lastScrollTop = st;
}
});
var nav = document.querySelector('.scroll-header');
var scrollUp = "header-show";
var scrollDown = "header-hide";
let lastScroll = 0;
window.addEventListener('scroll', () => {
const currentScroll = window.pageYOffset;
if (currentScroll <= 0) {
nav.classList.remove(scrollUp);
return;
}
if (
currentScroll > lastScroll &&
!nav.classList.contains(scrollDown) &&
!document.getElementById('sidecar').classList.contains('active')
) {
// down
nav.classList.remove(scrollUp);
nav.classList.add(scrollDown);
} else if (
currentScroll < lastScroll &&
nav.classList.contains(scrollDown)
) {
// up
nav.classList.remove(scrollDown);
nav.classList.add(scrollUp);
}
lastScroll = currentScroll;
});