Alter the font color upon clicking the menu using jQuery

When I click on the menu and sub-menu items, I want to change their colors along with their parent. You can see an example of how I want it to work here. However, currently, when I click on a sub-menu item, the color of the parent menu item gets removed.

$('li a').click(function() {

  $(' li a').removeClass('active'); {
    $(this).parent('a').addClass('active');
    $(this).addClass('active');

  }

});
.active {
  color: #DC0000 !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="navbar-collapse-grid" class="navbar-collapse collapse">
  <ul class="nav navbar-nav">
    <li class="dropdown yamm-fw">
      <a href="#" data-toggle="dropdown" class="dropdown-toggle">main menu<b class="caret"></b></a>
      <ul class=" navbar-nav dropdown-menu">
        <!-- Grid 12 Menu -->
        <li class="dropdown yamm-fw">
          <a href="#" data-toggle="dropdown" class="dropdown-toggle">menu1<b class="caret"></b></a>
          <ul id="menu1" class="dropdown-menu">
            <li class="grid-demo">
            </li>
          </ul>
        </li>
      </ul>
    </li>
  </ul>
</div>

Answer №1

$('li a').click(function () {
  // Remove active class from all nav links 
  $('ul.nav a').removeClass('active');

  // Add active class to clicked link
  $(this).addClass('active');

  // Add active class to parent links that are not in dropdown menu
  $(this).parents('li').find('a').filter(function () {
    return !$(this).closest('ul').hasClass('dropdown-menu');
  }).addClass('active');

  // Alternative approach
  // $(this).parents('li').find('a.dropdown-toggle').filter(function () {
  //    return !$(this).closest('ul').hasClass('dropdown-menu');
  // }).addClass('active');  
});

Example-1

Example-2

Answer №2

There is room for improvement in terms of cleanliness, perhaps reorganizing the classes could enhance targeting efficiency.

$('#navbar-collapse-grid a').click(function (e) {    
  // Remove all active classes
  $('#navbar-collapse-grid a').removeClass('active');

  $(this).closest('ul').parents('.dropdown').find('a').addClass('active');

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

http://codepen.io/anon/pen/PwoyYN

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

Creating a visually appealing multi-bar chart in AngularJS: Tips for effectively presenting data

Imagine that I have the JSON data below: [ { month: "Jan", cost: 80, energy: 90 }, { month: "Feb", cost: 50, energy: 80 }, { month: ...

Tips for obtaining a binary file sent through an HTTP:POST request using angular.js

I'm currently working on a project that involves using an Angular.js based viewer with a custom server. My goal is to implement an "execute & download" button. To send the request for execution, I am using an HTTP:POST method with specific headers: ...

Encountered an issue while attempting to include multiple JavaScript sources. Please review your configuration settings for the javascripts.join

While setting up a basic app using phoenix-elixir and brunch, encountering the following error: 23 Mar 10:18:10 - warn: node_modules/phoenix/priv/static/phoenix.js compiled, but not written. Check your javascripts.joinTo config 23 Mar 10:18:10 - war ...

Enhance User Experience with ngDialog Modal's Multi-pane Feature for Angular

Looking at the ngDialog example, they showcase a modal with multiple 'panes' that can be scrolled through: . After going through the ngDialog guide, I couldn't find a straightforward way to achieve this. Any suggestions on how to add a butt ...

Transferring an item from JavaScript to a controller method in MVC

Recently, I've encountered an issue with passing an object from a razor view to an action method. In my view: <section> <script type="text/javascript"> function saveExpense() { var expenseobject = { date:$(' ...

The PHP on server could not be loaded by Ajax

Trying to establish a PHP connection, encountering an error and seeking assistance. The error message displayed is as follows: { "readyState": 0, "status": 0, "statusText": "NetworkError: Failed to execute 'send' on 'XMLHttpReq ...

Setting the width of an SVG element to match the width of the <text> element inside it

Within this JSFiddle project - https://jsfiddle.net/xtxd6r8t/ - there is an <svg> element containing text inside a <text> tag. Upon inspection of the <svg> and delving into the <text> element, it's noticeable that the width of ...

IE7 encountering a mixed content error when using html5shiv and SSL

In the process of developing my ASP.Net application that utilizes html5shiv and SSL, I encountered mixed content errors in IE7 specifically when using html5shiv. Interestingly, removing html5shiv eliminated the errors. Additionally, my app incorporates upd ...

Seamlessly replacing an image in PixiJS without any sudden movement

I'm currently developing a HTML5 JavaScript game with a heavily textured background. My goal is to incorporate a 3D background element that can be swapped out dynamically. For example, the initial scene may show a room with a closed door, but once a J ...

AJAX response from open cart is returning null JSON data

Hey there, I'm having a problem with my ajax request. It seems like I keep receiving a null value for json. Let me show you the JavaScript code... <script> $(document).ready( function() { $('#donate-box-submit').on('click' ...

Guide on integrating a custom language parser and syntax validation into Monaco editor

I am in need of guidance on how to define a custom language in the Monaco editor. Despite my efforts, I have been unable to locate a reliable source for this documentation. My goal is to create a language with syntax similar to JavaScript, enabling users ...

Strategies to manage or prevent a timezone offset while deploying a Next.js application on Vercel

Is there a way to ensure that a React/Next.js App always displays the local time in CEST, regardless of the user's location? For example, if I receive GMT time from the backend and want to offset it to display the CEST timezone, how can I achieve this ...

What is the best way to include a file attachment using a relative path in Nodemailer?

I am currently utilizing the html-pdf converter plugin to transform an HTML page into a PDF file. After conversion, this plugin automatically saves the PDF to the downloads folder. When I attempt to attach a PDF to a nodemailer email, my code looks someth ...

Is it possible to utilize PHP to dynamically add a URL, media, and description on Pinterest?

Check out this code snippet: <script type="text/javascript"> (function() { window.PinIt = window.PinIt || { loaded:false }; if (window.PinIt.loaded) return; window.PinIt.loaded = true; function async_load(){ var s = document.createElement("scrip ...

How to handle Object data returned asynchronously via Promises in Angular?

Upon receiving an array of Question objects, it appears as a data structure containing question categories and questions within each category. The process involves initializing the object with board: JeopardyBoard = new JeopardyBoard();. Subsequently, popu ...

Creating a list of definitions in the form of an HTML table using a multidimensional array in

Currently, I am tackling the following challenge: I must create a public static buildDefinitionList() method that produces an HTML list of definitions (using <dl>, <dt>, and <dd> tags) and then returns the resulting string. If the array c ...

Fixing a CSS animation glitch when using JavaScript

I'm facing an unusual issue with my CSS/HTML Check out my code below: a:hover { color: deeppink; transition: all 0.2s ease-out } .logo { height: 300px; margin-top: -100px; transition: all 0.2s ease-in; transform: scale(1) } .logo:hover { transit ...

Unable to make the Show/Hide Loading GIF function work as intended

Could someone please help me with my code? I'm trying to display a loading GIF image while waiting for an ajax request to complete. When the button is pressed, I want the loader to be shown until the data is returned from the server. I would greatly ...

When a user clicks on a child element of an anchor tag, the function will

Is it possible to return a specific function when a user clicks on a child of an anchor element? <a href="/product/product-id"> I am a product <div> Add to favorites </div> </a> const handleClick = (event) =>{ ...

When interacting with elements with the "user-select: none" property, WkWebView still allows text selection

When using an iOS iPad app with a single fullscreen WKWebView, an issue arises when long-pressing on an area with user-select:none - the first text in the next available area without user-select:none gets selected instead of being ignored. Is there a way t ...