I have implemented a code in my website that will hide the navbar when scrolling down and show it when scrolling up.
the problem is I want when the user scroll up and stops scrolling to read something on the website after like 5 sec the navbar will hide again until the user starts scrolling again.
how can I do this?
this is the script I used for show/hide nav bar:
<script>
const nav = document.querySelector("nav");
const navHeight = 70;
// the point the scroll starts from (in px)
let lastScrollY = 0;
// how far to scroll (in px) before triggering
const delta = 10;
// function to run on scrolling
function scrolled() {
let sy = window.scrollY;
// only trigger if scrolled more than delta
if (Math.abs(lastScrollY - sy) > delta) {
// scroll down -> hide nav bar
if (sy > lastScrollY && sy > navHeight) {
nav.classList.add("nav-up");
}
// scroll up -> show nav bar
else if (sy < lastScrollY) {
nav.classList.remove("nav-up");
}
// update current scroll point
lastScrollY = sy
}
}
// Add event listener & debounce so not constantly checking for scroll
let didScroll = false;
window.addEventListener("scroll", function(e){
didScroll = true;
});
setInterval(function() {
if (didScroll) {
scrolled();
didScroll = false;
}
}, 250)
</script>
what can I add to it so the navbar will automatically hide when the user scrolls up and then stops scrolling?
5
Answers
You can try adding a timer that waits for some time after the user stops scrolling before hiding the navbar again:
Simply use a
setTimeout
function with a 5000ms timer to hide the navbar. Then use anaddEventListener
to reset the timer if a scroll event within the window occurred:The following snippet should do the trick.
Explanation: You want to add an eventlistener for scrolling the window, that sets a timeout of five seconds, before executing the onScrollStop function. Every time the user scrolls, we reset the timeout, because we want to wait five seconds, after the user STOPS scrolling, not when he stops for a just one or two seconds. If the condition (no scrolling for 5s) is met, we execute the onScrollStop function, which sets the display property of our header to none, making it disappear. Everytime the user scrolls, we set the header’s display property to unset, to make it appear. again.
Hope this helps
Happy coding!
The logic is pretty simple:
const isHide = isOffTop && !isScrollUp
Meaning: Hide the NAV when both the
window.scrollY
is greater thanelNav.offsetHeight
AND the scroll direction is "down"