I have a website with different sections identified by unique IDs, such as:
<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>
Additionally, I have a menu where each item corresponds to a section 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>
To ensure that the menu highlights the corresponding section as I scroll, I have jQuery code 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');
}
});
});
However, I am facing a problem where two menu items always highlight simultaneously as I scroll. I am looking for a solution to make sure only one menu item highlights when I scroll to a new section. Any help or guidance would be greatly appreciated!
Thank you!