DEV Community

Zain Muhammad
Zain Muhammad

Posted on • Edited on

6 2

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

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more