Dynamic Nav Bar
Keep users oriented. This script monitors the window scroll position and updates the navigation menu to reflect which section of the page is currently visible.
Section 1
Scroll down inside this box...
...
Section 2
Keep scrolling...
...
Section 3
You reached the end.
...
Copy the Script
<script>
window.onscroll = function() {
var sections = document.querySelectorAll("section");
var navLinks = document.querySelectorAll(".nav-link");
sections.forEach(sec => {
var top = window.scrollY;
var offset = sec.offsetTop - 100; // Adjustment
var height = sec.offsetHeight;
var id = sec.getAttribute("id");
if (top >= offset && top < offset + height) {
navLinks.forEach(links => {
links.classList.remove("active");
document.querySelector('a[href*=' + id + ']').classList.add("active");
});
}
});
};
</script>
Frequently Asked Questions
This specific script is designed for 'One Page' layouts (scroll spy). For multi-page sites, you would use server-side code (PHP) to add the 'active' class based on the filename.
Yes. You can adjust the pixel value in the scroll check logic to trigger the highlight earlier or later as the user scrolls.
Yes. We use the `scroll` event listener. For better performance on heavy sites, consider wrapping the function in a debounce or throttle function.