Author: | amdhanwate |
---|---|
Views Total: | 6,098 views |
Official Page: | Go to website |
Last Update: | August 17, 2021 |
License: | MIT |
Preview:

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:
- Smart Auto Show/Hide Header Navigation – Reveal-Bar
- Auto Show / Hide Sliding Header with Pure JavaScript – slidingHeader.js
- Responsive Show / Hide Navigation Menu with JavaScript and CSS3
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; })