DEV Community

Zain Muhammad
Zain Muhammad

Posted on

How to remove class on scroll top and add on scroll down on html body using JavaScript.

Here we are going to write simple JavaScript for remove class on html body on scroll top behavior and add class on scroll down behavior which is most used in mobile responsive web designs to show and hide site navbar. We can further hide and show the navbar with some CSS3 transitions (for make attractive) by using with the help of that class which is adding and removing with the help of JavaScript.

JavaScript snippet.

// javascript for remove class on scroll top and add on scroll down 
var lastScrollTop = 0;
var body = document.body;
window.addEventListener("scroll",function(){
var scrollTop = window.pageYOffset || document
.documentElement.scrollTop;
if(scrollTop > lastScrollTop){
    body.classList.remove("shownavbar");
}
else{
    body.classList.add("shownavbar");
}
lastScrollTop = scrollTop;
});
Enter fullscreen mode Exit fullscreen mode

on Scroll Top Behavior of JavaScript Screenshot

on Scroll Top Behavior of JavaScript Screenshot

on Scroll Down Behavior of JavaScript Screenshot

on Scroll Down Behavior of JavaScript Screenshot

Oldest comments (0)