Transforming a menu tab into an active anchor when navigating to a particular section

Hello,

I have successfully created a JavaScript code that can dynamically add menu tabs into the menu list

window.addEventListener("load", () => {
    
    const navList = document.getElementById("nav_list")
    
    const fragment = document.createDocumentFragment();
   
    const sections = document.querySelectorAll("section")
    
    const ui = document.querySelectorAll("ul")

   
    sections.forEach((sec) => {
        
        let data = sec.getAttribute("data-nav")

        let li = document.createElement("li")
        
        let text = document.createTextNode(data)
      
        li.classList.add("menu-link")

        let a = document.createElement("a")
        a.addEventListener("click", () => {
            sec.scrollIntoView({ behavior: 'smooth' })
        })

        a.appendChild(text)
        li.appendChild(a)
        fragment.appendChild(li)
    })

    navList.appendChild(fragment)

However, I am facing an issue in adding the active class to the tabs

This is the structure of the menu list in HTML

<nav class="navbar-menu">
        <h3>LOGO</h3>

        <div class="nav-bar">
            <label id="icon">
                <i class="fas fa-bars" onclick="toggle()"></i>
            </label>
            <ul id="nav_list" class="navbar-list"></ul>

        </div>
    </nav>

I am looking for a vanilla JavaScript solution to resolve this issue

Answer №1

Make sure to include the active class upon clicking within your event listener.

Potential fix:

const link = document.createElement("a")
    link.addEventListener("click", () => {
        section.scrollIntoView({ behavior: 'smooth' })
        removeActiveClasses()
        link.classList.add('active')

    })

function removeActiveClasses() {
   //iterate through navList array and remove active class from all child elements
}

Remember to also handle removing the class for each item in the navList to prevent multiple active navItems.

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

Switching URLs or internal pages using jQuery Mobile's select menu feature

Utilizing a select box as the navigation menu for my jQuery Mobile website. Some menu items link to internal pages while others link to external URLs. This is the code I'm using to change the page URL: $('#menu-select').change(function() ...

Incorporate clickable selection buttons into an HTML layout without disrupting the placement of existing

I have set up an HTML document that features a collection of buttons enclosed within a DIV id labeled 'buttons'. My objective is to introduce a sort by button into the mix without disrupting the current layout. I attempted to achieve this goal by ...

Node.js utilized for conducting anti-virus scans on server-bound files prior to uploading

Is there a way for me to scan files that are submitted as request payloads to check if they contain potential viruses? For example, if someone tries to upload a txt file with the EICAR virus signature, I want to be able to scan it and reject it if it is in ...

The footer section of my website seems to have gone missing in the HTML/CSS coding

I'm having trouble with my website footer not displaying. I've tried using "position: absolute; top: 50px; left:100px;" in my HTML/CSS, but it's not working. Can anyone help me fix this issue? Here is a link to the code I'm working on: ...

Experience the power of VueJS 3 with Pinia, all without the need

I've hit a wall. Despite scouring documentation and countless google searches, I can't seem to find the answer to this straightforward query: how do I install/import PINIA in a VUE application? Let's consider a basic VUE app: <div id=&qu ...

Is there a way to set a default CSS background image using JavaScript in case the specified

When working with regular CSS, I can easily set a fallback image using this code in case the primary image is not available: .container { background-image: url(pics/img.webp), url(pics/img.png); } But when it comes to setting styles in JavaScript (such ...

Is there a way to enable code completion for Firebase on VS Code?

After successfully setting up Typescript for code completion following the guidelines provided in this resource, I now want to enable code completion for Firebase in VS Code. However, I am unsure of the steps to achieve this. How can I activate code compl ...

Javascript is coming back with a message of "Access-Control-Allow-Origin" not being allowed

I've been encountering some unusual challenges with my React application related to the Access-Control-Allow-Origin issue. Initially, I had similar issues with the login and registration system which I thought were resolved, but now I'm facing di ...

Incorporate AJAX into your Javascript code for ordering

My issue arises when pointOnMap() is executed before xmlPreparer(), even though they are called in the correct order. I suspect this has something to do with the use of AJAX, as parseXML creates the object that pointOnMap() requires to be initialized befor ...

What is causing the error message "generator function required" to appear on my screen?

I recently installed the npm module called "koa-cache-control" and inserted the following code lines into my index.js file. const cacheControl = require('koa-cache-control'); After that... app.use(cacheControl({ noCache: true })); Upon sta ...

Exciting discovery within my coding for US Number formatting!

I am currently working on formatting 10 digits to resemble a US telephone number format, such as (###) ###-####. Although my code successfully achieves this goal, it also has an unexpected issue that I'm struggling to identify. Specifically, when ente ...

CombineReducers takes all the reducer content and unpacks it into a single reducer

As I work on developing a small application, I am contemplating the best strategy for organizing reducers within it. My objective is to retrieve JSON data from the application state and structure it as shown below: { "fruits": [ {"appl ...

How do I use NodeJS and MongoDB to dynamically populate my webpage with data from a database?

I am working on a small express + ejs application that stores data for registered users. Each user is assigned a "role" that is stored in the database. I would like to display each user's information in an html div, with the div's color refle ...

Adjusting mesh rotation on elliptical curve using mousewheel scrolling

I have arranged several plane meshes in a uniform manner along an elliptical curve. During the animation loop, I am moving them along the ellipse curve using curve.getPointAt with time delta and applying the matrix. Additionally, I am attempting to incor ...

Using jQuery's .html() method will remove the selected attribute from the dropdown menu option

When generating HTML dynamically, a select element is included. After choosing an option inside it, everything works fine. For example: <div id="test"> <select> <option value="1">1</option> <option value="2" selec ...

Using withRouter() to redirect will display all components

I'm brand new to Reactjs and am currently diving into routing. In my journey, I stumbled upon the use of withRouter() for programmatic redirection. I had assumed the flow would follow: constructor->Willmount->render, but it seems the current or ...

Error: Access Denied - discord.js bot command cannot be executed due to lack of authorization

Every time I initiate the bot and try to execute my "ping" command, an error occurs: js:350 throw new DiscordAPIError(data, res.status, request); ^ DiscordAPIError: Missing Access at RequestHandler.execute (C: ...

Asynchronously updating a Django model instance in real-time

On my website, there is a button that allows users to view notifications as a drop-down without navigating away from the current page. I am interested in updating the unread field of every notification for a user from True to False when this button is clic ...

Running JavaScript code within views

While dealing with AngularJS, I have an index page that includes a <div ui-view></div>. When a specific URL like #/offers/new is entered, it loads a page such as new-offer.html into the ui-view. In my javascript code block within the index.htm ...

Guide on how to capture tweets from particular Twitter profiles

I'm currently experimenting with the twitter npm package to stream tweets from specific accounts, but I'm facing some challenges. After reviewing the Twitter API documentation, I must admit that I am a bit perplexed. To fetch details about a pa ...