Navigation is an important part of any multipage website. Some people prefer links in a sidebar but most prefer a top navigation bar with all the prominent links in it.
The problem with top navigation bars is that when you scroll a long page, you get to the bottom of it and now you want to go to another page you will have scroll all the way backup.
People use back to top button to alleviate this but if your menubar was available everywhere, then you will not need this button.
We can stick the menu at the top so as to show all the time but it eats up a lot of precious space which can be used to show other useful content.
A smart way to tackle this is to use user behaviour to our advantage by using an intelligent navbar which detects scroll direction to show the nav.
A slight scrollup should show the navbar but scrolling down should hide it. Using the below snippet you can acheive this easily.
React
const [isScrollingUp, setIsScrollingUp] = useState(false);
useEffect(() => {
window.onscroll = function (e) {
setIsScrollingUp(this.oldScroll > this.scrollY);
this.oldScroll = this.scrollY;
};
});
Svelte/Vanilla
let isScrollingup = false;
window.onscroll = function (e) {
isScrollingup = this.oldScroll > this.scrollY;
this.oldScroll = this.scrollY;
};
window
object may not be directly accessible on Sveltekit. You will have to use onMount method or browser variable.