Unable to implement active class on parent li tab when child li is clicked

<div class="header_nav">
                    <ul id="navigation">

                        <li class="dropdown"><a href="#" rel="external">mainTab1</a>
                            <ul class="sub_navigation">
                                <li><a class="active" href="#">Sub Navigation 1</a></li>
                                <li><a href="#">Sub Navigation 2</a></li>
                                <li><a href="#">Sub Navigation 3</a></li>
                            </ul>
                        </li>

                        <li class="dropdown"><a href="#">MainTab2</a>
                            <ul class="sub_navigation">
                                <li id="tab_gad"><a href="#">Sub Navigation 1</a></li>
                                <li id="tab_iat"><a href="#">Sub Navigation 2</a></li>
                            </ul>
                        </li>
                    </ul>
                </div>

Is there a way to add the .active class to the parent li if a child li in the sub-navigation also has an active class?

In the code snippet above, one of the child li elements has an .active class. I tried the following code but it didn't work as expected.

$(".dropdown .sub_navigation li a").click(function(){
       $(this).closest('.dropdown').addClass("active"); // does not work
       $(this).closest('.dropdown').css("background", "blue"); // does not work
       $(".dropdown").css("background","red"); // works, but it highlights all .dropdown tabs, which is not the desired outcome. This was just a test to check if the function works
});

Essentially, I want both the child and parent elements to have the active class if a child tab is selected.

CSS

.dropdown:first-child a.active{
background: #672783;
}

.dropdown:nth-child(2) a.active{
    background: #ff6100;
}

Answer №1

Give this a try:

$(".dropdown .sub_navigation li a").click(function(){
    $(".active").removeClass('active');
    $(this).closest('.dropdown').find('a:first').addClass("active");
    $(this).addClass("active");
});

Here is a demonstration:

$(".dropdown .sub_navigation li a").click(function() {
  $(".active").removeClass('active');
  $(this).closest('.dropdown').find('a:first').addClass("active");
  $(this).addClass("active");
});
.active {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="header_nav">
  <ul id="navigation">
    <li class="dropdown"><a href="#" rel="external">mainTab1</a>
      <ul class="sub_navigation">
        <li><a class="active" href="#">Sub Navigation 1</a></li>
        <li><a href="#">Sub Navigation 2</a></li>
        <li><a href="#">Sub Navigation 3</a></li>
      </ul>
    </li>
    <li class="dropdown"><a href="#">MainTab2</a>
      <ul class="sub_navigation">
        <li id="tab_gad"><a href="#">Sub Navigation 1</a></li>
        <li id="tab_iat"><a href="#">Sub Navigation 2</a></li>
      </ul>
    </li>
  </ul>
</div>

Answer №2

$(".dropdown > .sub_navigation > li > a").click(function(){
       $(this).parents('li.dropdown').siblings('li').removeClass("active");
       $(this).parents('li.dropdown').addClass("active"); 

});

Demo:

$(".dropdown > .sub_navigation > li > a").click(function() {
  $(this).parents('li.dropdown').siblings('li').removeClass("active");
  $(this).parents('li.dropdown').addClass("active"); // not functioning properly

});
.dropdown:first-child a.active {
  background: #672783;
}

.dropdown:nth-child(2) a.active {
  background: #ff6100;
}

.active {
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="header_nav">
  <ul id="navigation">

    <li class="dropdown"><a href="#" rel="external">mainTab1</a>
      <ul class="sub_navigation">
        <li><a class="active" href="#">Sub Navigation 1</a></li>
        <li><a href="#">Sub Navigation 2</a></li>
        <li><a href="#">Sub Navigation 3</a></li>
      </ul>
    </li>

    <li class="dropdown"><a href="#">MainTab2</a>
      <ul class="sub_navigation">
        <li id="tab_gad"><a href="#">Sub Navigation 1</a></li>
        <li id="tab_iat"><a href="#">Sub Navigation 2</a></li>
      </ul>
    </li>
  </ul>
</div>

Answer №3

Give this a shot:

$(".dropdown .sub_navigation li a").click(function(){
    $(".active").removeClass("active");

    var $dropDown =$(this).closest('.dropdown');
    $dropDown.find("a:first").addClass("active");      

    $(this).addClass("active");  
});

DEMO

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

Attempting to align my navigation bar beside my logo

I've been attempting to position my navigation menu next to my logo, but it keeps displaying below it. Although my coding skills are not top-notch, I am aiming to have the nav element positioned alongside the logo, as shown in my design: HTML: <b ...

Find the location of the div element but ignore any divs with a certain class

<div class="center"> <div id="ContentTop" class="tt1">Top Content</div> <div id="abc" class="hide">exrt</div> <div id="bcd" class="hide">Content exta</div> <div id="MidContent" class="tcg">Mid ...

Generate available choices for an asp:DropDownList using JavaScript without relying on the client-side ID

Can options be populated in an asp:DropDownList using JavaScript without the need for getElementById? I prefer a selector that utilizes classes. Appreciate any assistance. Goodbye. ...

managing nested JSON arrays in JavaScript

I have a straightforward task with handling a simple array that is divided into two parts: a group of vid_ids and a single element named page. Initially, I was iterating through the vid_id array using a for loop. However, upon adding the page element, I en ...

Is there a way to achieve a transparent background while animating the second text?

I am seeking to create a unique typography animation that involves animating the second text, which is colored and consists of multiple text elements to animate. The animation should showcase each text element appearing and disappearing one after the other ...

The JSONP file can be successfully retrieved through an AJAX request in the console, however, the data does not display when attempting

Currently attempting to send an ajax request utilizing the following code snippet: $.ajax({ url: "http://mywebsite.com/blog/json", dataType: "jsonp", jsonpCallback: "jsonpCallback" }); function jsonpCallback(data) { console.log(data); } E ...

Steps to display a variable in JavaScript on an HTML textarea

I'm working on a JavaScript variable called 'signature' var signature; //(Data is here) document.write(signature) Within my HTML document, I have the following: <div id="siggen"> <textarea id="content" cols="80" rows="10">& ...

Ensure consistent switching of flexbox directional layout

I'm attempting to create a unique layout using only css3. My challenge is to achieve this without explicitly setting sizes, allowing the layout to flow freely. I am utilizing flexbox in my css for this purpose. After an automatic wrap, I want the layo ...

"Every time ajax is called, it will always generate

function lks() { var groupname = document.getElementById('groupname').value; $.ajax ({ url: 'verifyGroup.php?groupname='+groupname, type: 'get', ...

Ensure that the child div with a background color extends all the way to the bottom of its parent div

Having trouble getting two divs inside another one to stretch to the bottom without cutting off content? The goal is for both divs to adjust in height based on whichever one is longer, filling the outer div completely. When the left div (menu) is longer t ...

Sharing parameters between functions in JavaScript

I have a working code but I want to modify the function getLocation to accept 2 arguments that will be passed to getDistanceFromLatLonInKm within the ajmo function. Currently, getDistanceFromLatLonInKm has hardcoded arguments and I would like to use variab ...

Does ng-bind have the ability to function with input elements too?

My mind was spinning as I tried to figure out why my <input ng-bind="x.a * x.b" tabindex="-1" readonly/> expression wasn't functioning. The use of ng-model was not an option due to the fact that the product is not an L-value, so I made the swi ...

Adding a class to a clicked button in Vue.js

A unique function of the code below is showcasing various products by brand. When a user clicks on a brand's button, it will display the corresponding products. This feature works seamlessly; however, I have implemented a filter on the brands' lo ...

How to execute a doPostBack function within a jQuery click event

My current situation involves a js function that triggers a click event on all 'a' elements... $(document).ready(function hideRanges() { $('a').click(function (event) { $('.ranges, #UpdatePanel').hide(); }); }); ...

Background Color Not Displaying in CSS3 Preloader Code

Utilizing a CSS3 Designed Preloader for my website with some unique keyframe animations. #preloader { position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50 ...

What is the best way for me to collect messages submitted through a form on my website?

After completing my website using HTML, CSS, and JavaScript, I added a form with inputs for name, email, and message at the bottom of the page. Now, I am trying to figure out how to receive the information submitted by visitors in my email. ...

Steps for displaying an HTML table in Excel by clicking on a button

My goal is to open an HTML table in XLS format with a single click of a button. Currently, I have a JavaScript function that allows me to export the HTML table to XLS using the "save as" option. However, I want to enhance this functionality so that clickin ...

What is the best way to incorporate a progress bar animation into my notification?

Seeking assistance to implement an animated progress bar that changes colors gradually over time based on a variable [timer]. Can anyone lend a hand with this? Thank you! https://i.sstatic.net/lhgeF.png $(document).ready(function(){ window.addEvent ...

Combining two kebab-case CSS classes within a React component

import React from 'react'; import styles from './stylesheet.moudle.css' <div className={styles['first-style']} {styles['second-style']}> some content </div> What is the correct way to include styles[&ap ...

The issue with jQuery click function seems to be limited to Firefox

After a long hiatus from posting here, I hope this isn't breaking any rules. For those who prefer visual examples, you can visit the live page at: The drop-down menu functions perfectly in IE, Chrome, and Safari, but seems to be causing issues in Fir ...