jQuery - Whilst Scrolling Add/Remove Classes to Menu Items

Viewed 135

I have a website whereby it's made up of individual tags which have ID's laid out like the below (It has more HTML than below but I've trimmed it down for simplicity):

<section id="home">
    First Section
</section>
<section id="about_us">
    Second Section
</section>
<section id="what_we_do">
    Third Section
</section>
<section id="the_process">
    Fourth Section
</section>
<section id="contact">
    Fifth Section
</section>

I also have a menu like this where the li tags have classes with the corresponding text sections above:

<ul id="menu-main-menu" class="navbar-nav">
    <li itemscope="itemscope" id="menu-item-79" class="home menu-item menu-item-type-custom menu-item-object-custom nav-item menu-item-79"><a title="Home" href="#home" class="nav-link current_section">Home</a></li>
    <li itemscope="itemscope" id="menu-item-75" class="about_us menu-item menu-item-type-custom menu-item-object-custom nav-item menu-item-75"><a title="About Us" href="#about_us" class="nav-link current_section">About Us</a></li>
    <li itemscope="itemscope" id="menu-item-84" class="what_we_do menu-item menu-item-type-custom menu-item-object-custom nav-item menu-item-84"><a title="What We Do" href="#what_we_do" class="nav-link">What We Do</a></li>
    <li itemscope="itemscope" id="menu-item-81" class="the_process menu-item menu-item-type-custom menu-item-object-custom nav-item menu-item-81"><a title="The Process" href="#the_process" class="nav-link">The Process</a></li>
    <li itemscope="itemscope" id="menu-item-82" class="contact menu-item menu-item-type-custom menu-item-object-custom nav-item menu-item-82"><a title="Contact" href="#contact" class="nav-link">Contact</a></li>
</ul>

I then have some jQuery which detects whether the section is in the viewport, if it is it adds a class, if it isn't it removes the class like this:

$(window).scroll(function () {
    $('section').each(function() {
        var top_of_element = $(this).offset().top;
        var bottom_of_element = $(this).offset().top + $(this).outerHeight();
        var bottom_of_screen = $(window).scrollTop() + $(window).innerHeight();
        var top_of_screen = $(window).scrollTop();
        var id = $(this).attr('id');

        if ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
            $('.sticky_menu li.'+ id +' a').addClass('current_section');
        } else {
            $('.sticky_menu li.'+ id +' a').removeClass('current_section');
        }
    });
});

The problem is that two menu items always highlight as I scroll down the page. What I need it to do is once you scroll down and start a new section the corresponding menu item highlights.

Any help would be appreciate, I believe what I have is close but needs a tweak and needs to be simplified.

Thanks!

0 Answers
Related