Ways to update the CSS classes of a bootstrap navigation menu

I am working with a bootstrap navigation bar that includes an option called "Add New Candidate" as a list item. I need to update its class from "nav-item has-treeview" to "nav-item has-treeview menu-open" when the user selects it, and also change the class of the "General Information" unordered list inside the "Add New Candidate" to "nav-link active".

For possible solutions, I have referred to this article on Bootstrap CSS Active Navigation

Please find the images of the navigation bar and the expected outcome below:

Navigation Bar image

Expected Outcome

Here is the code snippet:

$(document).ready(function(){
  $('.nav nav-pills nav-sidebar flex-column li').click(function(e) {
    var $this = $(this);
    if (!$this.hasClass('nav-item has-treeview')) {
      $this.addClass('nav-item has-treeview menu-open');
    }
    e.preventDefault();
  });
 
  $('.nav nav-pills nav-sidebar flex-column li a').click(function(e) {
    var $this = $(this);
    if (!$this.hasClass('nav-link')) {
      $this.addClass('nav-link active');
    }
    e.preventDefault();
  });

  $('.nav nav-treeview li a').click(function(e) {
    var $this = $(this);
    if (!$this.hasClass('nav-link')) {
      $this.addClass('nav-link active');
    }
    e.preventDefault();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false">
<li class="nav-item has-treeview">
<a href="addnewCandidate" class="nav-link">
        <i class="nav-icon fas fa-tachometer-alt"></i>
        <p>Add new Candidate <i class="right fas fa-angle-left"></i></p>
    </a>

    <ul class="nav nav-treeview">
        <li class="nav-item"">
            <a href="addnewCandidate" class="nav-link">
                <i class="far fa-circle nav-icon"></i>
                <p>General Information</p>
            </a>
        </li>
           
        <li class="nav-item" >
            <a href="educationInfo" class="nav-link">
                <i class="far fa-circle nav-icon" id="education" ></i>
                <p>Education</p>
            </a>
        </li>
       
        <li class="nav-item">
            <a href="trainingInfo" class="nav-link">
                <i class="far fa-circle nav-icon"></i>
                <p>Training</p>
            </a>
        </li>

        <li class="nav-item">
            <a href="workExperienceInfo" class="nav-link">
                <i class="far fa-circle nav-icon"></i>
                <p>WorkExperience</p>
            </a>
        </li>


        <li class="nav-item">
            <a href="languageInfo" class="nav-link">
                <i class="far fa-circle nav-icon"></i>
                <p>Language</p>
            </a>
        </li>
    </ul>
</li>
</ul>

Answer №1

It appears that there was an incorrect handling of the class selector in JavaScript. For example:

Incorrect handling of the class selector

$('.nav nav-pills nav-sidebar flex-column li').click(function(e) {

Correct handling of the class selector

$('.nav.nav-pills.nav-sidebar.flex-column li').click(function (e) {

$(document).ready(function () {
  $('.nav.nav-pills.nav-sidebar.flex-column li').click(function (e) {
    if ($(this).hasClass('has-treeview')) {
      $(this).toggleClass('menu-open');
    }
    e.preventDefault();
  });

  $('.nav.nav-treeview li a').click(function (e) {
    if ($(this).hasClass('nav-link')) {
      $('a').removeClass('active')
      $(this).addClass('active');
    }
    e.preventDefault();
  });
});
.nav {
  font-family: arial;
}
.nav .nav-item .nav-link{
  color: #000;
  text-decoration: none;
}

.nav .nav-item .nav-link.active{
  color: green;
  font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false">

  <li class="nav-item has-treeview">
    <a href="addnewCandidate" class="nav-link">
      <i class="nav-icon fas fa-tachometer-alt"></i>
      <p>
        Add new Candidate
        <i class="right fas fa-angle-left"></i>
      </p>
    </a>

    <ul class="nav nav-treeview">

      <li class="nav-item">
        <a href="addnewCandidate" class="nav-link">
          <i class="far fa-circle nav-icon"></i>
          <p>General Information</p>
        </a>
      </li>


      <li class="nav-item">
        <a href="educationInfo" class="nav-link">
          <i class="far fa-circle nav-icon" id="education"></i>
          <p>Education</p>
        </a>
      </li>

      <li class="nav-item">
        <a href="trainingInfo" class="nav-link">
          <i class="far fa-circle nav-icon"></i>
          <p>Training</p>
        </a>
      </li>

      <li class="nav-item">
        <a href="workExperienceInfo" class="nav-link">
          <i class="far fa-circle nav-icon"></i>
          <p>WorkExperience</p>
        </a>
      </li>

      <li class="nav-item">
        <a href="languageInfo" class="nav-link">
          <i class="far fa-circle nav-icon"></i>
          <p>Language</p>
        </a>
      </li>
    </ul>
  </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

What's the reason my code isn't functioning as expected?

I am currently working on a website script that changes text based on a specific link, but I am facing issues with the code. The script is supposed to pull data from a MySQL database named ftvo and a table named seriesdb using the link format /file.php?s-i ...

Creating a custom button in PHP

Currently, I am in the process of developing a shopping cart feature. One key requirement is to send both the product ID and the desired quantity chosen by the user to another file named cart.php. Below is an excerpt from my code snippet: for($i=0;$i< ...

Transforming JavaScript array UNIX timestamps into JavaScript Date objects

Is there a way to convert UNIX epoch integers into JavaScript Date objects using jQuery? Attempting to pass a large JSON array generated by PHP to Highmaps.JS, which works almost great. However, Highmaps expects a Date object and Date objects aren't ...

Guide to making a Java Servlet for a specific jQuery.ajax () request?

In one of my files named wfd.proxy.js, I have the following code snippet: if (!WFD) { var WFD = {}; }; if (!WFD.Proxy) { WFD.Proxy = {}; }; WFD.Proxy = { SERVICE_URL : "/delegate/WFD/WFService?", PDF_SERVICE_URL : "/delegate/pdf-exporter?", ...

Master the art of manipulating tags in Django templates using JavaScript

In my Django quiz app, there are two main components. The first part involves displaying 10 sentences with corresponding audio to help with memorization, one per page. The second part consists of asking questions based on the same set of sentences. I initi ...

Positioning Multi-level Drop Down Div in Javascript - How to do it efficiently?

I'm currently working on a horizontal menu using CSS and JavaScript with multiple levels. I've implemented a toggle function to show the submenu container, but it's causing the links below it to be pushed down. Is there a way to make the dis ...

Using JQuery to locate radio buttons that have been selected based on a variable

In my JavaScript code, I have created a variable called "thisRadio" to represent a dynamically generated div containing multiple radio buttons. Currently, one of these radio buttons may be checked and my goal is to find the checked radio button within this ...

What is the best way to retrieve a value from an `<input type="number">` element and incorporate it into the script section?

Check out this code snippet <html> <head> head <title>title</title> </head> <script> var val1 = parseInt(document.getElementById('input1')); function bytton() { window.alert(val1); ...

Is it possible to add a computed value to the bar's end in Chart.JS?

I'm creating a bar graph that has two bars representing different weeks. Currently, it looks like this: https://i.stack.imgur.com/6Avni.png However, I want it to look like this: https://i.stack.imgur.com/TAVqe.png In order to achieve the desired r ...

Encountering issues with implementing bootstrap-datepicker on cloned rows, as the values remain locked to the first date field

Encountered an issue with cloning rows using bootstrap-datepicker and bootstrap. To reproduce the problem: 1. Select a date in the first input field (id_form-0-expense_date_item). 2. Add another row and select a date in the second input field, which shoul ...

Adjusting the width of the responsive design is causing additional white space to appear in

I have a website that uses responsive CSS, including media queries at 768px, 480px, and 320px. However, when I resize the screen below 1040px, I notice some extra space appearing on the right margin of the entire page and I'm struggling to identify th ...

Why do certain list items on my page have a gap between their border and content?

I recently encountered an issue with my list of items and their styling. Each list item contains an anchor element with a gray background, while the item itself has a gradient bottom border. However, I noticed that in some cases, there was a white line ap ...

Utilizing Dojo DGrid to customize the appearance of data within cells

I am facing an issue with my dgrid where I want to style cells by underlining the text when the checkboxes are selected for the row. My initial approach was to add a CSS class to the item once the checkbox is checked for the row. However, this method did ...

I could use some help navigating payment gateways

I'm new to payment gateways and would appreciate any recommendations or advice. ...

Is it possible to have setTimeOut() executed after the page has been redirected?

Why is it not possible to duplicate: The question was not addressed in the previous post. I have a link for deletion, which, when clicked, triggers a popup with a button. Upon clicking that button, the page inside the popup redirects to a new internal pag ...

Looking to retrieve a specific data element within Vue.js?

Here's a thought-provoking query for you. Imagine I have some data stored in an element in the form of an array like this: data: { product: socks, variants: [ { variantId: 2234, variantColor: 'Green', varian ...

Automated Recommendation Selector

I'm searching for a JavaScript library that can provide the following functionalities: An auto-suggest dropdown list that uses Ajax to retrieve results from a database. Restricting the user to only select values provided by the Ajax call. Abilit ...

How do I hide a dropdown menu when the selector's value changes in iOS6?

I'm currently developing a hybrid application using Worklight. When I tap on a select control, a native dropdown appears. However, when I choose an option and the onchange event is triggered, the dropdown doesn't disappear unless I tap on the do ...

Problem with the transparency of CSS, div, and asp:Image

I am facing an issue with a div that has its opacity set to 60. Within this div, there is an asp:Image element. It seems like the opacity of the div is also affecting the image inside it. I attempted to create a separate class for the image and adjust th ...

Implementing the display of bootstrap modal with error message upon page reload in CodeIgniter

Currently, I have a popup model that allows users to add a course name. In my Codeigniter controller, I have implemented form validation. If the validation fails, I reload the view with an error message displayed above the form input in the modal. However, ...