Adding an active class to a menu when its submenu is clicked in JavaScript

Is it possible to add an active class to a parent menu when clicking on its sub-menu in Bootstrap? Below is the Bootstrap menu code:

// Active navigation
const currentLocation = location.href;
const menuItem = document.querySelectorAll('.nav-link');
const menuLength = menuItem.length;

for (let i = 0; i < menuLength; i++) {
  if (menuItem[i].href === currentLocation) {
    menuItem[i].classList.add("active");
  }
}
.active {
  color: #FF0000;
  border-bottom: 2px solid #FF0000;
}
<ul class="navbar-nav m-auto">
  <li class="nav-item ">
    <a class="nav-link active" href="index.html">Home</a>
  </li>
  <li class="nav-item dropdown">
    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
             About
           </a>
    <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
      <a class="dropdown-item " href="about.html">About me</a>
      <a class="dropdown-item" href="myportfolio.html">My portfolio</a>
      <a class="dropdown-item" href="contact.html">Contact</a>
    </div>
  </li>

  <li class="nav-item">
    <a class="nav-link" href="demo.html">Demo</a>
  </li>
</ul>

How can I make a parent menu active even after clicking on its sub-menu and being redirected to another page? Any help would be appreciated.

Answer №1

To implement a click event, you can utilize the method addEventListener...


const dropdown = document.querySelector("#navbarDropdownMenuLink");
const dropdownItem = document.querySelectorAll(".dropdown-item");

for (let i = 0; i < dropdownItem.length; i++) {
  dropdownItem[i].addEventListener("click", function() {
    dropdown.classList.add("active");
  });
}
.active {
  color: #FF0000;
  border-bottom: 2px solid #FF0000;
}
<ul class="navbar-nav m-auto">
  <li class="nav-item ">
    <a class="nav-link active" href="index.html">Home</a>
  </li>
  <li class="nav-item dropdown">
    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
             About
           </a>
    <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
      <a class="dropdown-item " href="#">About me</a>
      <a class="dropdown-item" href="#">My portfolio</a>
      <a class="dropdown-item" href="#">Contact</a>
    </div>
  </li>

  <li class="nav-item">
    <a class="nav-link" href="#">Demo</a>
  </li>
</ul>




Additional Resources:


Answer №2

If you're looking to activate the menu that shows the link of a specific location after the page reloads or redirects following a click on the menu, this code snippet will help achieve that effect. It simulates the behavior of the 'location' property using a fake location variable. The comparison between links and the current location is made possible by leveraging the URL API.

// Activate navigation
const fakeLocation = new URL("/myportfolio.html", "https://example.com/").pathname;

// Loop through the menu items
document.querySelectorAll('li.nav-item')
  .forEach(link => {
      const links = [...link.querySelectorAll("a")];

      link.classList.remove("active");
      links.forEach(lnk => lnk.classList.remove("active"));

        const shouldBeActive = links.find(lnk =>
          new URL(lnk.href).pathname === fakeLocation);

        if (shouldBeActive) {
          shouldBeActive.classList.add("active");
          shouldBeActive.closest("li").classList.add("active");
        }
      });
.active {
  color: #FF0000;
  border-bottom: 2px solid #FF0000;
  background-color: #eee;
}
<base href="https://example.com/">
<ul class="navbar-nav m-auto">
  <!-- currently active -->
  <li class="nav-item active">
    <a class="nav-link active" href="index.html">Home</a>
  </li>
  <li class="nav-item dropdown">
    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
         About
       </a>
    <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
      <a class="dropdown-item " href="about.html">About me</a><br>
      <a class="dropdown-item" href="myportfolio.html">My portfolio</a><br>
      <a class="dropdown-item" href="contact.html">Contact</a><br>
    </div>
  </li>

  <li class="nav-item">
    <a class="nav-link" href="demo.html">Demo</a>
  </li>
</ul>

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

Guide on how to modify the CSS styling of a particular <td> element when its parent contains a specific class

.webgrid-table td, th { border: 1px solid #98bf21; padding: 3px 7px 2px; } I am facing an issue where the style defined above is being applied to all td elements. However, I want to exclude the styling for a td that is within a tr element with the ...

JavaScript Animation of Text

I have a challenge where I want to animate text's opacity in JavaScript after the user presses enter. However, I am struggling to achieve this with my current code. I can provide all of my code for you to review and help me understand why the animatio ...

Show the present category name within breadcrumbs (utilizing angularJS)

Struggling to display category and vendor names on breadcrumbs? Utilizing the ng-breadcrumbs module but encountering difficulties in making curCategory and curVendor globally accessible. Tried various methods without success. Below is the HTML code snippe ...

Caution: Highlighting Non-ASCII Characters in Your Django Form

Looking to implement client-side Ajax validation for my Django form. The goal is to alert users in real-time if any non-ascii characters are detected as they type in a field. Originally considered using python to check for ascii characters in the form&apo ...

Does each HTML element have a one-to-one correspondence with a DOM element at all times?

Can an element be present in the DOM without appearing in the HTML code? And can it also be the other way around? ...

Add the bannercode snippet found on a webpage

I am currently facing an issue with appending a banner code to the end of a URL. The scenario is as follows: An individual receives an email with a link to a website (SITE1), where the URL includes a banner code, such as www.site1.com?banner=helloworld O ...

Unable to retrieve the HTML select value in the AJAX response

In the process of my code, there are two main steps. The first step involves a user filling in certain fields and then submitting the data to the server using ajax. Once submitted, the server returns an HTML select input that requires the user to choose a ...

Running Vanilla JS scripts in a React application after the DOM has been rendered

After spending 5 hours scratching my head trying to resolve this issue, I encountered a problem with placing <script> tags in the index.html file located within the public folder. I need these scripts to run only after the HTML has been fully rendere ...

What is the best way to create a tooltip that appears when a user hovers over text within an <ins> tag?

Alright, I've defined a custom <ins> tag with the following CSS: ins{ color:blue; font-weight:500; text-decoration:none; } ins:hover{ cursor: pointer; cursor: hand; text-decoration:underline; } I'd like to add a ...

Incorporate JSON and JavaScript into your website template

Currently, I am in the process of developing my online resume using a free template that I found and downloaded. The template incorporates bootstrap and showcases a progress bar indicating my skills. However, I want to take it a step further by dynamically ...

It is not possible to decrease the size of the image that is currently used as the background image

Three images are arranged in this manner: https://i.stack.imgur.com/u4PdK.png The HTML code for this setup is as follows: <div class="lb-controlContainer"> <div class="lb-closeContainer"> <a class="lb-close"&g ...

Updating an attribute while customizing a CSS style: A step-by-step guide

This question is a continuation of my previous inquiries. I have a CSS file that needs to be included (first_style.css in the code snippet below). The necessary style is img { height:auto; }. Any additional styles can be added before or after this line. O ...

What is the best way to pass an array of 8-digit strings from an input in Angular to a Node.js backend?

I am currently facing a challenge where I need to pass an array of 8 digit strings from an Angular input to a Node.js endpoint. The method below works perfectly fine when passing a single string, but how can I handle an array of 8 digit strings as input? ...

Struggling with making the ajax request

Having trouble handling the response from a URL called through AJAX. The URL returns a response when accessed directly from the browser, but encountering difficulties when using it in the AJAX call. Have tried using both responseText and responseXML proper ...

Creating a password with two distinct numbers using regular expressions

In javascript I am struggling to create a password that meets the criteria of having at least eight characters, including two SEPARATE digits, one uppercase and one lowercase letter, as well as one special character (-, @, #, $, &, *, +) but not /, !, ? ...

What steps do I need to take to create a dynamic rowspan within Vuetify?

I am currently working on creating a table that resembles the image provided in the link below. https://i.sstatic.net/xWa1I.png I understand that I can achieve this by using nested data and multiple iterations with the help of the template feature offere ...

Struggling to receive information from a third-party API using a token in a React application

Currently, I am attempting to retrieve data from a third-party API. While it functions properly on Postman, I am striving to successfully make a request and access the data within my React project. The public API in question is: https://api.securityscorec ...

Is there a way to adjust the size of a table display to ensure that both vertical and horizontal scroll bars are constantly visible?

[edits added below per the request to see code. Edits also added to the original post to clarify the ask - marked in bold] My application features a broad table with the potential for many rows, generated by django-tables2 using the bootstrap5-responsive ...

Have you ever wondered how to disable a tooltip in React Material UI after clicking on it? Let

I am working with a Material-UI tab component and I would like to include a tooltip feature. The issue I am facing is that the tooltip does not disappear when I click on the tab. It should hide after clicking on the tab. Currently, the tooltip remains vi ...

Add a span tag with the class "javascript" around the index of a character within a string

Within an element, I have a string as such: <p>I like trains and planes</p> Using jQuery's .text(), I extract the text and store it in a variable. var str = $('p').text(); I aim to identify a specific character, let's sa ...