How do I dynamically adjust class names for menu items as I scroll using jQuery?

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!

Answer №1

Here's a suggestion for you:

(top_of_window >= top_of_object) && (top_of_window < bottom_of_object)

Answer №2

It seems like the concept here involves creating a scrollable container and highlighting the links associated with the sections that are currently in view.

In this scenario, a grid layout with a sticky header was used as the scrollable container. Some CSS styles were applied to visually demonstrate the scrollable container.

  • The goal is to highlight the links that are visible in the Y axis.
  • Handling window resize events by triggering the scroll is also implemented.
  • Instead of dealing with the attached class, a scroll event is triggered on startup within the container.
  • Credit is given to the code borrowed from , with some jQuery involved, although it could be achieved using vanilla JavaScript as well.

A restructured JavaScript function was utilized to determine the visibility of an element in the viewport. This function is responsible for updating the highlighted section within the menu accordingly.
The provided CSS styles define the layout of the page with a grid structure and scrollable main block. Additionally, styles for the header, sections, and footer are included to enhance the visual representation of the scrollable container.
The HTML structure contains a navigation menu and main content sections encapsulated within a scrollable container. Each section is assigned an ID and corresponding data attributes to facilitate the highlighting of menu items based on visibility.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using JavaScript to Detect Asynchronous Postbacks in ASP.NET AJAX

Seeking advice on the JavaScript code required to determine if an asynchronous postback is in progress. Can anyone help with this? Appreciate any assistance. ...

React Native Material - Implementing a loading indicator upon button press

With React Native Material, I am trying to implement a loading feature when a button is clicked. The goal is to show the "loading" message only when the button is active, and hide it otherwise. Additionally, I would like for the loading message to disappea ...

Multiple variable evaluation in Javascript does not function properly

Currently, I have an array that I am looping through in order to create variables. The variable names are derived from the array itself and I am using eval (only on my local machine) to achieve this. Interestingly, I can successfully create a variable and ...

Spread out a div across a container's width

Currently, I am struggling to modify my css and html in order to have a div expand horizontally into a scrollable div. However, all I seem to get is the content stacking once the width limit is reached. Take a look at this fiddle for reference. The absol ...

Error: An unexpected token '<' was encountered during the React Webpack build process

My ReactJs project is using Webpack4 and @babel/core 7. However, when I attempt to build the project, I encounter the following error in the terminal: ERROR in ./src/views/Pages/Login/Login.js Module build failed (from ./node_modules/babel-loader/lib ...

Creating a recursive setTimeout loop using Coffeescript

I am currently developing a live photo stream application. The idea is that users will be able to upload photos to a specific folder on my server via FTP, and the app should automatically update whenever a new photo is added, without needing to refresh the ...

What is the Best Way to Enable Tooltips to Function from External Elements?

I am currently designing a map that features points with tooltips. When hovered over, the tooltips function correctly. I am interested in exploring the possibility of making the tooltips interact with an external navigation bar. My goal is to have specifi ...

Preventing Text Truncation in THREE.js Texture Created from 2D Canvas

Many people tend to use the 2D canvas texture method for creating text billboards, sprites, and overlays in THREE.js scenes instead of relying on imported image files. You can check out an example by Lee Stemkoski here. However, I have noticed that when a ...

What methods can I use to create a peer-to-peer communications platform with PHP, MySQL database, and JavaScript?

Currently, I am encountering the challenge of creating a communication channel between two users on a website (such as a gaming site) using only the technologies specified in the title. I recently created an online chess platform with the aim of allowing ...

What steps can I take to change my single-line navbar into a two-line design?

Lately, I've been working on a website with a navbar that looks like the one in this https://i.sstatic.net/5ptAj.png image. However, I want to change my navbar to look more like the one in this https://i.sstatic.net/KiHCf.png image. I've attemp ...

What is the best way to extract the ID from an event in TypeScript?

HTML Code: <ion-checkbox color="dark" checked="false" id="1on" (ionChange)="onTap($event)" ></ion-checkbox> TypeScript Code: onTap(e) { console.log(e); console.log(e.checked); } I am trying to retrieve the id of the checkbox. H ...

What is the established procedure for resetting all elements within an (X)HTML document?

Is there a way to reset elements without using a form like how it can be done with JavaScript? document.forms[0].reset(); I am utilizing AJAX, so do I need to loop through all the elements using JavaScript? ...

Arranging Bootstrap Cards in an Orderly Stack

I recently created a set of bootstrap cards displayed like this: <div class="card-deck"> <div class="card"> <img class="card-img-top" src=".." alt="Card image cap"> <div class="card-body"> <h5 cl ...

Vorlon.js is requesting Socket.io, even though its configuration already includes socket.io

Whenever I try to load the app, a red div appears in front with the message: Vorlon.js: make sure to load socket.io before referencing vorlon.js or set includeSocketIO = true in your catalog.json file. Every time I access the server page, my terminal d ...

generating dynamically evolving controls within the MVC framework

I am looking to dynamically create controls in a view based on the source. For example, if the type is a text box, I want to generate a text box; if it is a check box, I want to create a check box dynamically in MVC. Below is the snippet of my current code ...

Deliver the GWT module in JavaScript format

Currently, I am in need of the following: I need to create a GWT module that can be seamlessly incorporated into a GWT app without requiring recompilation - essentially a plug-and-play solution. This module should include a widget along with various cla ...

Looping through multiple ajax requests to track the most recent responses

Run a loop with the most recent response obtained from the previous ajax call. The current code is continuously displaying the same response. PHP outputs data in text format. Currently, the code fetches response text from the PHP file and appends it to a ...

How come I can't capture discord.js promise rejections within event callbacks?

As I delve into creating a discord bot, I encountered an interesting problem. To simplify things, here is a snippet that encapsulates the issue at hand: const Discord = require('discord.js'); const client = new Discord.Client(); client.on(&apo ...

Enhancing the appearance of a JSX component in React

I have a segment of code within my project that calculates a specific percentage and displays it on the dashboard. <text className="netProfit-circle-text" x="50%" y="50%" dy=".2em" textAnchor="middl ...

Node JS HTTP proxy stalling out

Seeking assistance with an http-proxy setup that proxies any website and injects a custom JS file before serving the HTML back to the client. Experiencing issues where accessing the proxied website results in a hang-up or indefinite loading in the browser. ...