Show/Hide Navbar On Scroll Down Or Up

Category: Javascript , Menu & Navigation | August 17, 2021
Author:amdhanwate
Views Total:6,098 views
Official Page:Go to website
Last Update:August 17, 2021
License:MIT

Preview:

Show/Hide Navbar On Scroll Down Or Up

Description:

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.

<header>
  ... navbar here ...
</header>
<main>
  ... main content here ...
</main>
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;
main.style.top = headerHeight + "px";
let lastScroll = 0;
window.addEventListener("scroll", () => {
  let currentScroll = window.pageYOffset;
  if (currentScroll - lastScroll > 0) {
    header.classList.add("scroll-down");
    header.classList.remove("scroll-up");
  } else {
    // scrolled up -- header show
    header.classList.add("scroll-up");
    header.classList.remove("scroll-down");
  }
  lastScroll = currentScroll;
})

You Might Be Interested In:


Leave a Reply