An Interest In:
Web News this Week
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
- April 18, 2024
- April 17, 2024
Hide NavBar as Scroll down, in less than 10 lines of javascript;
You must have seen this effect on several website, where you scroll down and navigation bar automatically hides and reappears when scroll up.
So here's basic page in which I have implemented this,in just 10 lines of javascript.
var lastScrollTop;
navbar = document.getElementById('navbar');
window.addEventListener('scroll',function(){
var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
if(scrollTop > lastScrollTop){
navbar.style.top='-80px';
}
else{
navbar.style.top='0';
}
lastScrollTop = scrollTop;
});
How it's working
Here, the position of the navbar is being altered using javascript.
First we create a variable which stores position of Page;
Then we get the scroll position using: window.pageYOffset
or for some browser 'document.documentElement.scrollTop';
Then check that weather the page is scrolled up or down;
Then save the scroll vale to the variable;
This is done every time whenever the page is scrolled, as all this lies under a EventListener
.
Check the JS in codepen it will make it more clear
Original Link: https://dev.to/areeburrub/hide-navbar-as-scroll-down-in-less-than-10-lines-of-javascript-1i00
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To