Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 24, 2021 06:21 pm GMT

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

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To