Search code examples
javascripthtmlcssuinavigationbar

change menuitem based on scroll position using javascript


Changing the menu item in navigation bar based on scroll position using javascript.

i have changed the menu item on click. but don't know how to change the active menu item based on scroll position. I have tried getting the pageYoffset. it is a very long process and too looks like repetition. is this the right way to do it or is there an efficient way to do so.

HTML CODE:

<nav class="navbar navbar-expand-lg navbar-light">
    <div class="collapse navbar-collapse" id="navbarNav">
        <ul class="navbar-nav">
            <li id="home" class="nav-item active">
                <a class="nav-link" href="#homeSection"><i class="fa fa-home"></i></a>
            </li>
            <li id="about" class="nav-item">
                <a class="nav-link" href="#aboutSection"><i class="fa fa-user"></i></a>
            </li>
            <li id="skill" class="nav-item">
                <a class="nav-link" href="#skillSection"><i class="fa fa-cogs"></i></a>
            </li>
            <li id="work" class="nav-item">
                <a class="nav-link" href="#workSection"><i class="fa fa-eye"></i></a>
            </li>
            <li id="contact" class="nav-item">
                <a class="nav-link" href="#contactSection"><i class="fa fa-envelope"></i></a>
            </li>
        </ul>
    </div>
</nav>

JAVASCRIPT:

let header = document.getElementById("navbarNav");
let btns = header.getElementsByClassName("nav-item");
for (var i = 0; i < btns.length; i++) {
    btns[i].addEventListener("click", function () {
        let current = document.getElementsByClassName("active");
        current[0].className = current[0].className.replace(" active", "");
        this.className += " active";
    });
}

Solution

  • The code can be minimised using jquery. BUt if you want to use javascript alone, you will have a little longer code. Get the scolltop value of each section during scroll event and assign the active class