javascript always active sidebar first link

I'm currently using the code below for my sidebar. The issue I'm facing is that the first link in the sidebar always appears active, even when clicking on the second or third links. The other links work as expected, where the active state moves to the clicked link. How can I fix this so that the first link behaves like the others?

    document.addEventListener("DOMContentLoaded", function() {
        const sidebarWrapper = document.getElementById('sidebar-wrapper');
        const closeButton = document.getElementById('close-sidebar');
        const currentPath = window.location.pathname;

        console.log("Current Path:", currentPath);

        document.querySelectorAll('#sidebar .list-group-item').forEach(function(link) {
            const linkPath = new URL(link.href).pathname;

            console.log("Link Href:", linkPath);

            if (currentPath.includes(linkPath)) {
                link.classList.add('active');
                console.log("Active Link:", link);
            }
        });

        if (closeButton) {
            closeButton.addEventListener('click', function() {
                if (sidebarWrapper) {
                    sidebarWrapper.classList.toggle('collapsed');
                }
            });
        } else {
            console.error("Close button with ID 'close-sidebar' not found.");
        }
    });

Answer №1

It is important to remove the "active" class from the old URL that matches and add the "active" class to the link that was just clicked on.

This action should be performed both when the page loads and when a link is clicked on.

In the future, please include a runnable code snippet so that those trying to assist you do not have to create multiple HTML and CSS elements to match your JavaScript. Thank you.

You can test the code snippet below to view the code in action.

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

Dealing with Laravel and AJAX - Issue with Loading DIV

I find myself in a perplexing situation. Despite not encountering any errors in my apache logs or browser (chrome), I am faced with an issue that has left me baffled. On a specific page (localhost/admin/networks), I can click on an item from a database-ge ...

CSS only rendering in Firefox, not displaying in other browsers

After all the hard work I put into my website, I have encountered an issue while conducting browser compatibility checks. There seems to be something strange happening with the CSS of a specific link. I have applied a CSS class and included some PHP code ...

Guide to creating a .htm webpage that can process characters from non-English languages

I’m currently developing an application that converts .msg files to PDF format. I’ve been using a PDF converter that translates HTML files into PDFs, so my process involves converting the email to HTML before using the tool for conversion. Everything w ...

Discover the positions of the y-axis tick marks with d3.js

I have been working on creating an SVG visualization using d3.js (specifically version 3 of d3 in PowerBI) and I am encountering difficulties in aligning my data points and fixed lines with the correct y-axis tick markers. When there are 8 axis points, th ...

The content on my HTML webpage exceeds the width of the screen on mobile devices and certain PCs

I've exhausted most of the solutions available online, yet I haven't been able to resolve the issue. The content on my webpage is appearing wider than the screen size on mobile devices and some PCs URL: html, body,{ max-width: 100%; ...

A type error was thrown: $.ajax function does not exist within another function

I encountered a persistent ajax error on the website. Error : Uncaught TypeError: $.ajax is not a function at Hei Here is my code for reference: Can anyone pinpoint where I may be going wrong? The suggested solutions from other sources have not resol ...

Creating full-width bootstrap buttons within the navbar

Currently, I am utilizing bootstrap to design the navbar on my website. My goal is to have three buttons within the navbar that, when clicked, will navigate to other pages. Currently, my navbar looks like this: https://i.sstatic.net/31s1f.jpg However, th ...

Ways to incorporate white spaces into text when utilizing the .text() method

Currently, I am utilizing a combination of angularJS and jQuery to work with the tooltip widget and a drop-down menu. Our goal is to extract names from a multi-select field, and when multiple items are chosen from the dropdown menu, we want to display the ...

Is the function for identifying the polygon in which a coordinate is located not functioning correctly?

Seeking a function to identify which polygons a coordinate falls within? Check out this function in the GitHub project: https://github.com/mikolalysenko/robust-point-in-polygon. Testing the function with the provided syntax gives the correct result (retur ...

Avoiding repetition in json array using reactjs with the help of axios

After receiving guidance from @Akrion, I managed to resolve the issue! Check out my comments below our conversation for the solution. I am relatively new to reactJS and axios, but I recently collaborated with a classmate on a project. Now, I find myself s ...

Using AJAX to send data from knockout observables to the server in JSON format

I'm currently facing an issue where I am trying to send form fields that are linked to specific observables to my server as a JSON object, but I keep receiving an empty JSON string on the server side. I want to avoid sending the entire view model just ...

PHP - fwrite() or fputs() Can Occasionally Mishandle Accented Characters

I have been developing a PHP application that generates an HTML file as its final output. However, I am facing a problem where French characters are inconsistently written to the file incorrectly (this is not happening on the webpage itself, as when I view ...

Footer Message

Check out my website at I want to add a small link on the red footer bar in the bottom right corner. I have designed an image to demonstrate what I am trying to accomplish. Can someone guide me on how to make this happen?? ...

Is anyone else experiencing issues with loading a font from a CDN? It works perfectly fine on Chrome Browser and Safari for iOS Simulator, but for some reason, it's not loading

It's driving me a bit crazy as I'm not sure where I've gone wrong. I'm currently working with NextJS and have loaded this font into my <Link />. While it displays perfectly on Chrome and Safari in the iOS simulator, it fails to l ...

Sizing a full screen background image with CSS

Recently delving into the world of HTML and CSS, I've grasped a few fundamental concepts. Seeking assistance from those more experienced to tackle this perplexing issue. I am currently working on a webpage that calls for a full-screen background imag ...

What is preventing my Grails application from retrieving an object from my Angular script?

I'm currently working on adding objects to a JSON list in Grails. Below is the Angular code I am using: http://pastebin.com/4ypijUMD Additionally, here is my Grails controller: http://pastebin.com/skTtVtxv My understanding is that the angularJS scri ...

Social Count Total Using AddThis HTML Plugin

Our Blog uses AddThis to enable sharing of our posts. We want to track the total number of shares across all networks in one consolidated section, rather than displaying individual share counts for each network. This is the current code snippet: < ...

Ways to create a downward expanding navigation menu when collapsed

Trying to accomplish the following, please refer to the image below. I am looking to have the yellow bar extend down when the collapsed menu is open. Currently, the navigation links are hidden behind the logo as shown in the second image below. https://i. ...

Invoke a PHP function by utilizing a JavaScript AJAX post call

I have been exploring various topics extensively, but I have not been able to find a solution. My objective is to create an HTML hyperlink that triggers a Javascript AJAX post request on a PHP page to execute a PHP function (potentially with any number of ...

Adjust the video resolution by selecting various sources that direct to alternate quality options

Objective: I aim to create a streamlined control system that allows for easy adjustment of video quality with minimal code. Preferences: Although I have certain limitations, I prefer to avoid reinventing the wheel by creating a custom video control sche ...