WebTuts - seomat.com

Your ultimate destination for comprehensive, easy-to-follow web tutorials.

Change the navigation color based on the section background while scrolling in JavaScript

To dynamically change the navigation color based on the section background color while scrolling, you can use JavaScript and CSS.

Changing the navigation color based on the section background while scrolling is a dynamic and visually appealing web design technique. This approach enhances the user experience by providing a clear visual indication of the user's current position on the page.

Let's start by creating the HTML structure. For less complexity, I'll use the Bootstrap 5 Framework.

Navigation

Just a simple navigation menu structure. Each anchor will point out to a section.

<nav class="nav">
    <a class="nav-link" href="#section-1">Section 1</a>
    <a class="nav-link" href="#section-2">Section 2</a>
    <a class="nav-link" href="#section-3">Section 3</a>
    <a class="nav-link" href="#section-4">Section 4</a>
    <a class="nav-link" href="#section-5">Section 5</a>
</nav>

Main content sections

Each section represents a distinct part of your webpage. To better exemplify the functionality, I will add the colors of a zebra (white, black, white, black, etc.).

<div class="container-fluid p-0">
    <section id="section-1" class="bg-white">Section 1</section>
    <section id="section-2" class="bg-black">Section 2</section>
    <section id="section-3" class="bg-white">Section 3</section>
    <section id="section-4" class="bg-black">Section 4</section>
    <section id="section-5" class="bg-white">Section 5</section>
</div>

JavaScript functionality

The last thing we need to do is to create the JavaScript functionality that will listens to the load and scroll event. Using the changeNavColor function, the navigation background color will be changed according to the background color of the currently visible section.

const changeNavColor = () => {
    const scrollPosition = window.scrollY;
    const sections = document.querySelectorAll("section");

    sections.forEach((section, index) => {
        const sectionTop = section.offsetTop; // get section offset
        const sectionHeight = section.clientHeight; // get section height

        if (scrollPosition >= sectionTop && scrollPosition < sectionTop + sectionHeight) {
            const sectionBg = section.classList[0];
            const nav = document.querySelector("nav");

            nav.classList.remove("bg-white", "bg-black");

            if (sectionBg === "bg-black") {
                nav.classList.add("bg-white");
            } else {
                nav.classList.add("bg-black");
            }
        }
    });
}

window.addEventListener("load", () => changeNavColor());
window.addEventListener("scroll", () => changeNavColor());

Adjust the styling and logic as needed for your specific design.

Demo

See the Pen Untitled by Stanescu Eduard-Dan (@ZsharE) on CodePen.