Show/Hide Navbar On Scroll Down Or Up

Category: Javascript , Menu & Navigation | August 17, 2021
Views Total:8,243 views
Official Page:Go to website
Last Update:August 17, 2021


Show/Hide Navbar On Scroll Down Or Up


A smart and user-friendly sticky navbar component that automatically shows and hides itself depending on the scroll direction.

It listens for scroll events, determines whether the page is scrolled up or down, and then applies corresponding CSS classes to the navbar.

See Also:

How to use it:

1. Create a fixed header navbar on the page.

  ... navbar here ...
  ... main content here ...
header {
  display: flex;
  justify-content: space-between;
  padding: 2rem 5rem;
  background: #4F46E5;
  color: #fff;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  transition: all 300ms ease;
  z-index: 10;

2. Apply ‘scroll-up’ or ‘scroll-down’ CSS classes to the navbar based on the scroll direction.

const body = document.body;
const header = document.querySelector("header");
const main = document.querySelector("main");
const headerHeight = document.querySelector("header").offsetHeight; = headerHeight + "px";
let lastScroll = 0;
window.addEventListener("scroll", () => {
  let currentScroll = window.pageYOffset;
  if (currentScroll - lastScroll > 0) {
  } else {
    // scrolled up -- header show
  lastScroll = currentScroll;

You Might Be Interested In:

Leave a Reply