Update all items in the menu to be active, rather than only the chosen one

Here is the layout of my menu along with the jQuery code included below. The functionality is such that when I click on Home Page, its parent element (list item) receives an active class.

Currently, when I am on the Home Page, the list item for Account Codes and Branches also have an active class applied. How can I ensure that only the Home Page is affected?

Additionally, how can I modify the jQuery code to accommodate this nested list format in the menu?

<ul class="sidebar-menu" id="navigation-menu">
    <li><a href="/" class="nav-link"><i class="far fa-square"></i><span>Home Page</span></a></li>
    <li class="menu-header">Administrator Mode</li>
    <li class="nav-item dropdown">
        <a href="#" class="nav-link has-dropdown"><i class="fas fa-fire"></i><span>Configuration</span></a>
        <ul class="dropdown-menu">
            <li><a href="/Configuration/Account Codes" class="nav-link">Account Codes</a></li>
            <li><a href="/Configuration/Branches" class="nav-link">Branches</a></li>
        </ul>
    </li>
</ul>


<script>
    $(document).ready(function () {
        var current = location.pathname;
        $("#navigation-menu a").each(function () {
            var $this = $(this);
            if ($this.attr('href').indexOf(current) !== -1) {
                console.log($this);
                $this.parent().addClass('active');
                console.log("matched");
            }
        });
    });
</script>

Answer №1

Effective Dropdown Menu Layout

A practical HTML layout strategy for dropdown menus involves utilizing alternating sets of <ul>/<ol> and <li> elements:

<ul>
   <li class='dropdown'>
     <a href="#/">Dropdown</a>
     <ul class='menu' style='display:none'>
      <li>Item</li>
      <li class='dropdown'>
        <a href='#/'>Dropdown</a>
        <ul class='menu' style='display:none'>
          <li>Item</li>
          <li>Item</li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

If you prefer the menus to be initially hidden, include the following inline style:

<ul class='menu' style='display:none'>

The default behavior of <a> tags can be challenging to modify when working with frameworks like Bootstrap or Foundation. Consider toggling the .active class on child tags of .has-dropdown.


Interactive Demo

Additional details provided in the demo:

/*
Delegate click event to each .has-dropdown
Toggle .active class on that particular .has-dropdown children tags
Get next .dropdown-menu and toggle it up/down and toggle .active
*/
$('.has-dropdown').on('click', function(e) {
  $(this).children().toggleClass('active');
  $(this).next('.dropdown-menu').slideToggle().toggleClass('active');
});
.active {
  color: tomato
}
<link href='https://cdnjs.cloudflare.com/ajax/libs/foundation/6.5.3/css/foundation.min.css' rel="stylesheet">
<link href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" rel="stylesheet" crossorigin="anonymous">

<ul id="navigation-menu" class="sidebar-menu">
  <li>
    <a href="#/" class="nav-link">
      <i class="fas fa-home"></i><span> Home Page</span>
    </a>
  </li>
  <li class="menu-header">
    <a href="#/" class="nav-link has-dropdown">
      <i class="fas fa-tools"></i><span> Administration</span>
    </a>
    <ul class="nav-item dropdown-menu" style='display:none'>
      <li>
        <a href="#/" class="nav-link has-dropdown">
          <i class="fas fa-lock"></i><span> Security</span>
        </a>
        <ul class="dropdown-menu" style='display:none'>
          <li>
            <a href="#/" class="nav-link">
              <span> Account Codes</span>
            </a>
          </li>
          <li>
            <a href="#/" class="nav-link">
              <span> Branches</span>
            </a>
          </li>
        </ul>
      </li>
      <li>
        <a href="#/" class="nav-link has-dropdown">
          <i class="fas fa-cog"></i><span> Configuration
        </span></a>
        <ul class="dropdown-menu" style='display:none'>
          <li>
            <a href="#/" class="nav-link"><span> Layout</span></a>
          </li>
          <li>
            <a href="#/" class="nav-link"><span> Assets</span></a>
          </li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

Encountering difficulties loading a Partial View using a JQuery ActionResult request in ASP.NET Core

I've been struggling with this issue for what seems like forever. Although I can initiate the ActionResult that returns PartialView("MODEL"), I'm having trouble rendering the actual View into the div within the Index cshtml page. Here's wh ...

Press on any two table cells to select their content, highlight it, and save their values in variables

I have a table retrieved from a database that looks like this (the number of rows may vary): |Player 1|Player 2| ------------------- |Danny |Danny | |John |John | |Mary |Mary | My goal is to select one name from each Player column and sto ...

Utilizing Jquery's Selectable IDs in a repetitive manner

I'm a newbie to jQuery and I'm attempting to create two lists where each item can be selected. Check out my code: <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI s ...

What could be causing this function to work in Google Chrome, but not in Firefox?

For some reason, in Firefox, this section of the code never returns true. However, it works perfectly fine in Google Chrome. if(restrictCharacters(this, event, digitsOnly)==true) The expected behavior is that if a user inputs a number from 1 to 5 in the ...

Are you familiar with using double conditional rendering in a React application?

Currently, I am in the process of creating a small clothing store application using React as a way to expand my skills. One feature I have implemented is a filter by price section. However, I am looking for a solution to handle cases where no items fall wi ...

Updating the unordered list (UL) of rows in MySQL dynamically

Currently working on a test site that aims to function as a video playlist player pulling videos from the VIMEO API based on URL numbers (like vimeo.com/7100569) The setup involves storing a list of these URLs in a MySQL table. At this stage, I have manag ...

getStaticProps function in Next.js fails to execute

My [slug].js file includes two Next.js helper functions, getStaticPaths and getStaticProps. These functions are exported and create the path posts/[slug]. I have also added a post file named hello.json. However, when I try to access localhost:3000/posts/he ...

Looping the jQuery Ajax success function

Utilizing Ajax to input an array of data into a database. At the moment, when clicking on "#bookingbutton," it triggers a return block of HTML containing the ".select-room-button" button. I have incorporated the code for ".select-room-button" within the ...

Leveraging JQuery to extract the numerical value located between the slashes within a hyperlink

I need to extract numeric values from a link like this. For example: /produkt/114664/bergans-of-norway-airojohka-jakke-herre In this case, I want to fetch 114664. To achieve this, I have written the following jQuery code: jQuery(document).ready(functi ...

Enhancing Angular input validators with updates

Working on a project with Angular 6, I have set up an input field using mat-input from the Angular Material framework and assigned it an id for FormGroup validation. However, when I initialize my TypeScript class and update the input value, the validator d ...

Utilize JavaScript to include HTTP headers in image requests

In my JS/HTML5 Project with angularjs, I have implemented protection for my API by setting an authorization token in the HTTP header. Now, I am also looking to secure access to images stored on the server. While I know how to accomplish this on the server ...

When submitting a form with the jQueryForm plugin, take action on the form by selecting it with `$(this)`

I have a situation where I have multiple forms on one page and am utilizing the jQuery Form plugin to manage them without having to reload the entire page. The issue arises when I need some sort of visual feedback to indicate whether the form submission wa ...

jQuery tooltip plugin - DelayIn not functioning as expected

I recently installed the jquery tipsy plug-in on my website, but I'm having trouble getting it to work properly. The fade effect works perfectly and the HTML displays correctly, but the delay doesn't seem to be working as expected. Here is the co ...

Issues with Formik sign-up

Working on a study project involving React, Typescript, Formik, and Firebase presents a challenge as the code is not functioning correctly. While authentication works well with user creation in Firebase, issues exist with redirection, form clearing, and da ...

What is the best way to establish anchors for *ngFor elements in Angular 2 and beyond?

I have a component that displays items using *ngFor. My goal is to scroll down to the element with anchor #3. Here's the code snippet: @Component({ selector: 'my-app', template: ` <button (click)="scroll(3)">scroll 2</butt ...

"Vue js: Embracing Labeling and Agile Transformation in Dynamic

Is it possible to dynamically change the input field's type and label between text, email, and number in Vue.js? I am new to this framework and would like to learn how to do this. <input type="email"> ...

The issue lies with the Cookies.get function, as the Typescript narrowing feature does not

Struggling with types in TypeScript while trying to parse a cookie item using js-cookie: // the item 'number' contains a javascript number (ex:5) let n:number if(typeof Cookies.get('number')!== 'undefined'){ n = JSON.pars ...

Issue with Vue class binding failing to update when state is modified

I'm attempting to utilize Vue class binding depending on the index within the v-for loop. While I can see that the state in Vue dev tools is changing correctly, the class name itself isn't being updated. <div class="group" v-for= ...

Is this the correct method for linking the function to every individual element?

Is it correct to attach the function to each element individually? Also, is my function correctly implemented? <ul id='forShopping'> <li><input class='ch' type='checkbox' onclick='isAct ...

What is the best way to incorporate custom events into classes using Node.js?

Recently delving into node, I have a question about adding custom events to a class. In the code below, I attempted to create a simple farm class where the number of animals changes and triggers an event called totalChanged. let events = require('eve ...