Tips for adding and removing active class with navbar links using JavaScriptonclick

I need help with toggling the "li-active" class on my navigation bar links. Currently, when I click on a link, the "li-active" class is transferred from the previous link to the newly clicked link instead of removing it first. Can someone please assist me in solving this issue? Thank you!

 <li data-id="0" id="mercury" class="navbar__links--li">
              <div class="inner-div">
                <div class="mercury-oval"></div>
                MERCURY
              </div>
              <svg
                class="svg"
                xmlns="http://www.w3.org/2000/svg"
                width="6"
                height="8"
              >
                <path fill="none" stroke="#FFF" opacity=".4" d="M1 0l4 4-4 4" />
              </svg>
            </li>
            <li data-id="1" id="venus" class="navbar__links--li">
              <div class="inner-div">
                <div class="venus-oval"></div>
                VENUS
              </div>
              <svg
                class="svg"
                xmlns="http://www.w3.org/2000/svg"
                width="6"
                height="8"
              >
                <path fill="none" stroke="#FFF" opacity=".4" d="M1 0l4 4-4 4" />
              </svg>
            </li>
            <li data-id="2" id="earth" class="navbar__links--li li-active">
              <div class="inner-div">
                <div class="earth-oval"></div>
                EARTH
              </div>
              <svg
                class="svg"
                xmlns="http://www.w3.org/2000/svg"
                width="6"
                height="8"
              >
                <path fill="none" stroke="#FFF" opacity=".4" d="M1 0l4 4-4 4" />
              </svg>
            </li>
            <li data-id="3" id="mars" class="navbar__links--li">
              <div class="inner-div">
                <div class="mars-oval"></div>
                MARS
              </div>
              <svg
                class="svg"
                xmlns="http://www.w3.org/2000/svg"
                width="6"
                height="8"
              >
                <path fill="none" stroke="#FFF" opacity=".4" d="M1 0l4 4-4 4" />
              </svg>
            </li>
            <li data-id="4" id="jupiter" class="navbar__links--li">
              <div class="inner-div">
                <div class="jupiter-oval"></div>
                JUPITER
              </div>
              <svg
                class="svg"
                xmlns="http://www.w3.org/2000/svg"
                width="6"
                height="8"
              >
                <path fill="none" stroke="#FFF" opacity=".4" d="M1 0l4 4-4 4" />
              </svg>
            </li>
            <li data-id="5" id="saturn" class="navbar__links--li">
              <div class="inner-div">
                <div class="saturn-oval"></div>
                SATURN
              </div>
              <svg
                class="svg"
                xmlns="http://www.w3.org/2000/svg"
                width="6"
                height="8"
              >
                <path fill="none" stroke="#FFF" opacity=".4" d="M1 0l4 4-4 4" />
              </svg>
            </li>
            <li data-id="6" id="uranus" class="navbar__links--li">
              <div class="inner-div"&...

.li-active {
  @include desktop {
    border-top: 1px solid red;
  }
}
menuBtn.forEach((li) => {
  li.addEventListener("click", (e) => {
    menuBtn.forEach((el) => el.classList.remove("li-active"));
    e.target.classList.add("li-active");
  });
});

https://i.sstatic.net/T1zTB.jpg

Answer №1

One reason is that the class is being added to the clicked target, which may not be the direct parent element.

To address this issue, simply add the class to the clicked element itself (li.classList.add):

let linkItems = document.querySelectorAll('.menu__item')

    linkItems.forEach((li) => {
        li.addEventListener("click", (e) => {
            linkItems.forEach((el) => el.classList.remove("active"));
            li.classList.add("active");
        });
    });

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

I am unable to view the map on my webpage. This issue only arises when I apply a CSS style to it

Hey there! I'm having trouble displaying a map on my website. For some reason, the map is not showing up even after updating the Google secret key in my code: <?php session_start(); include '../../WSweb/serv.php'; if(isset($_SESSION[&a ...

Issue with Angular 7 service worker caching audio files leads to range header problems in Safari browser

I am encountering an issue in my Angular application with the range request header for audio files when using Safari. When requesting audio from a server, the duration of the audio file is returned correctly. However, when requesting the audio from the ser ...

What is the best way to find the average time in Typescript?

I am dealing with an object that contains the following properties: numberOfReturns: number = 0; returns_explanations: string [] = []; departure_time: string = ''; arrival_time: string = ''; The departure_time property hold ...

What is the best way to use jQuery to adjust the size of a slider image based on a percentage of the browser window

I've been searching all over for a solution to this issue, but so far I haven't had any luck. Basically, I have an image that is 1800 pixels wide by 500 pixels high. I need this image to adapt to all screen resolutions. Instead of having a fixed ...

Leveraging concealed input for transmitting additional information via asynchronous JavaScript and XML (Ajax

My current approach involves using hidden inputs to include extra values with Ajax when a form is submitted by a user. The rationale behind this strategy is that I have a lengthy list of text fields, each accompanied by a button. Upon clicking any button, ...

How can I edit this code in JSPDF to print two pages instead of just one?

Currently, I have a script that can generate a PDF from one DIV, but now I need to create a two-page PDF from two separate DIVs. How can I modify the existing code to achieve this? The first DIV is identified as #pdf-one and the second DIV is #pdf-two. p ...

The Chrome (version 58) webdriverio is currently inactive, while Firefox is up and running

Previously, I successfully ran automation tests on Firefox and Chrome locally. However, there seems to be an issue that has arisen when trying to run them on Chrome recently. My system configurations: Operating System: Windows 10 (64-bit) Chrome Versio ...

Automatically trigger a PHP reload/refresh based on user input

My website has a form that populates a table with data. Currently, after the user submits the data, they have to manually refresh the page in order to see the new data displayed. Is there a way to automatically refresh the table every time the user hits ...

What is the method for linking to another page ID using an <a href> tag?

On one of my pages, I have a section that references another page's div id to trigger a click event for editing specific form fields. This is the profile page: <a href="<?php echo base_url('settings_pro/edit'); ?>" name="pull-righ ...

Creating artwork: How to resize images without losing clarity

Struggling to display an image in a canvas element that needs to be a certain percentage of its parent container's width. Despite my efforts, the image seems to blur once added to the canvas, which is not the desired effect. I attempted to disable th ...

Issues encountered when trying to implement helperText in mui date picker

Can someone assist with this issue? The helper text is not displaying as expected in the following code snippet: <div className={classes.container}> <LocalizationProvider dateAdapter={AdapterDateFns}> <Des ...

Transferring live data between AJAX-triggered pop-up windows

Utilizing modals frequently in my application is a common practice. There are instances where I need to transfer data from one modal box to another. For instance: Suppose there is a table listing different car manufacturers (Audi, BMW, Honda, etc). Each r ...

Remove chosen tags from the options list in Material UI Autocomplete Multiple

When utilizing the Material UI Autocomplete for multiple values, the selected input is shown in the options list with a blue background color. Is there a way to configure the autocomplete to exclude already selected values from appearing in the options li ...

Is there a way to obtain the guild ID during the createGuild event?

Can someone please help me figure out how to get the guild id in the event guildCreate.js? I have tried using guild.id but it returns undefined. Even when I use console.log(guild), it shows a blank space. Using client.guild.id throws an error for id. cons ...

Is it possible to use JQuery to target input nodes based on their values?

How can I check if any of the file input boxes in my list have a value using just one selector statement? Is it possible to achieve this with code like the following: $('input:file[value!=null]') Or is there another way to accomplish this? ...

Retrieve a specific item from a JSON response using Node.js

When I receive a message from a WebSocket, the code snippet is triggered like this: ws.onmessage = (e) => { debugger if (e.data.startsWith('MESSAGE')) alert(JSON.stringify(e.data)) ImageReceived(e.data) c ...

Using a background image from your own website does not display anything, but using an image from an

It's really strange from where I'm standing. I'm working on a website and trying to set up a banner with a background image using the background-image property. The issue I'm facing is: when I use two images with the same dimensions, ...

How can I properly implement a Closure or IIFE to manage an onclick event in ReactJS?

I'm encountering an issue while attempting to utilize the this object in an event handler. An undefined error related to the this object keeps popping up. My development stack includes ReactJS and Redux as well. class Chat extends Component { c ...

Importing modules in Node can be done after the code has been executed, or through ESM Dynamic

I am currently working on a project in nodejs and express, and I am facing an issue where I need to execute certain code before importing modules. The app is already set up to use import for modules instead of require, and changing this setting is not an o ...

the reason for the blurring of shadows in Three.js

Typically, the shadow appears as shown below: https://i.sstatic.net/5L9N2.png However, upon adjusting the parameters of directionalLight.shadow.camera directionalLight.shadow.camera.left = -50 directionalLight.shadow.camera.right = 50 directionalLight.s ...