Ad

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" target="_blank" rel="nofollow noreferrer" href="#homeSection"><i class="fa fa-home"></i></a>
            </li>
            <li id="about" class="nav-item">
                <a class="nav-link" target="_blank" rel="nofollow noreferrer" href="#aboutSection"><i class="fa fa-user"></i></a>
            </li>
            <li id="skill" class="nav-item">
                <a class="nav-link" target="_blank" rel="nofollow noreferrer" href="#skillSection"><i class="fa fa-cogs"></i></a>
            </li>
            <li id="work" class="nav-item">
                <a class="nav-link" target="_blank" rel="nofollow noreferrer" href="#workSection"><i class="fa fa-eye"></i></a>
            </li>
            <li id="contact" class="nav-item">
                <a class="nav-link" target="_blank" rel="nofollow noreferrer" 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";
    });
}
Ad

Answer

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

Ad
source: stackoverflow.com
Ad