nav-scroll.js
This script toggles the visibility of a sticky header based on scroll direction. It hides the header when the user scrolls down and reveals it when the user scrolls up.
Overview
nav-scroll.js tracks the page’s vertical position and adds or removes a CSS class to control header visibility. It depends only on vanilla JavaScript and manipulates an element with the ID hideOnScroll.
How It Works
- On load, it records the initial scroll offset.
- It listens for the
window.onscrollevent. - It compares the new offset to the previous one.
- If the user scrolled down, it adds the class
topHide. - If the user scrolled up, it removes that class.
- It updates the stored offset for the next scroll event.
Code Breakdown
var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
var element = document.getElementById("hideOnScroll");
if (prevScrollpos < currentScrollPos) {
element.classList.add("topHide");
} else {
element.classList.remove("topHide");
}
prevScrollpos = currentScrollPos;
};
- prevScrollpos: stores the last known vertical offset.
- currentScrollPos: reads the new offset on each scroll.
- element: references the DOM node with ID
hideOnScroll. - topHide: CSS class that triggers the hiding animation.
Key Variables
| Name | Type | Default | Description |
|---|---|---|---|
prevScrollpos |
Number | window.pageYOffset |
Last recorded vertical scroll position. |
currentScrollPos |
Number | — | Vertical scroll position on each event. |
element |
Node | #hideOnScroll element |
Header element to show/hide via class toggle. |
topHide (CSS) |
Class | Defined in external stylesheet | Hides header when added. |
Integration 🎯
- Ensure your header has the ID
hideOnScroll. - Include
nav-scroll.jsafter that element in your HTML. - Define
.topHidein CSS to animate the hide/show.
Example HTML
<header id="hideOnScroll" class="main-header">
<!-- your logo and navigation here -->
</header>
<script src="new_2025_js/nav-scroll.js"></script>
Suggested CSS
#hideOnScroll {
position: fixed;
top: 0;
width: 100%;
transition: transform 0.3s ease;
z-index: 1000;
}
#hideOnScroll.topHide {
transform: translateY(-100%);
}
Considerations
- Null checks: If
#hideOnScrollis missing,getElementByIdreturnsnulland throws errors. Add a guard if needed. - Performance: The script uses a simple scroll listener. For heavy pages, consider throttling or debouncing.
- Customization: Adjust the CSS transition duration to match your design.
🚀 Key Takeaways
- nav-scroll.js provides a lightweight solution for hiding headers on scroll.
- It uses only native browser APIs for maximum compatibility.
- You can easily adapt CSS to suit various layouts and animations.