What is the best way to toggle the active class on a ul list?

After clicking, the active class remains on the original "li" instead of changing as it should. I've tried modifying the code but haven't been able to find a solution. Can someone please review what I might have missed? It seems like there's something specific to my code that I'm missing. I looked into "adding/removing an active class for UL list with jQuery," but that didn't solve the issue. Any help in pinpointing the error in my code would be greatly appreciated.

HTML:

<div class="collapse navbar-collapse navbar-ex1-collapse">
    <ul class="nav navbar-nav navbar-right">
        <li class="active"><a href="#juk">About</a></li>
        <li><a onclick="myFunction1()">Development</a></li>
        <li><a href="http://docs.kde.org/stable/en/kdemultimedia/juk/index.html">Wiki/Documentation</a></li>
        <li><a onclick="myFunction()">Screenshots</a></li>
        <li class="dropdown">
        <a data-toggle="dropdown" class="dropdown-toggle" href="#">Releases </a>
        <ul class="dropdown-menu">
            <li><a href="ftp://ftp.kde.org/pub/kde/stable/latest">JuK Latest</a></li>
            <li><a href="http://developer.kde.org/~wheeler/files/src/juk-1.95a.tar.gz">JuK 1.95</a></li>
            <li><a href="http://developer.kde.org/~wheeler/files/src/juk-1.1.tar.gz">JuK 1.1</a></li>
            <li><a href="http://developer.kde.org/~wheeler/files/src/juk-1.0-1.tar.gz">JuK 1.0</a></li>
        </ul>
        </li>
        <li><a href="#contactus">Contact Us</a></li>
    </ul>
</div>

JavaScript:

$(function() {
    ( 'ul.nav.navbar-nav.navbar-right li' ).on( 'click', function() {
        $( this ).parent().find( 'li.active' ).removeClass( 'active' );
        $( this ).addClass( 'active' );
    });
});

Answer №1

You have mistakenly targeted the wrong <li> element in the .on('click') event

Your initial selector was:

$( 'ul.nav navbar-nav navbar-right li' )

This will search for a li that is a child of navbar-right which is a child of navbar-nav which is also a child of ul.nva.

The correct selector should be:

$( 'ul.nav.navbar-nav.navbar-right li' )

Note the space before the li? This indicates that it is a descendant of the ul element with multiple classes.

I understand that you followed the class list from the HTML DOM element, but remember to avoid spaces in jQuery selectors when targeting an element with multiple classes.

$(function() {
  $('ul.nav.navbar-nav.navbar-right li').on('click', function() {
    $(this).parent().find('li.active').removeClass('active');
    $(this).addClass('active');
  });
});
.active {
  background-color: gold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div class="collapse navbar-collapse navbar-ex1-collapse">
  <ul class="nav navbar-nav navbar-right">
    <li class="active"><a href="#juk">About</a></li>
    <li><a>Development</a></li>
    <li><a href="#">Wiki/Documentation</a></li>
    <li><a >Screenshots</a></li>
    <li class="dropdown">
      <a data-toggle="dropdown" class="dropdown-toggle" href="#">Releases </a>
      <ul class="dropdown-menu">
        <li><a href="#">JuK Latest</a></li>
        <li><a href="#">JuK 1.95</a></li>
        <li><a href="#">JuK 1.1</a></li>
        <li><a href="#">JuK 1.0</a></li>
      </ul>
    </li>
    <li><a href="#contactus">Contact Us</a></li>
  </ul>
</div>

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

Efficiently transferring input to a Typescript file

Is there a better way to capture user input in Angular and pass it to TypeScript? <form > <input #input type="text" [(ngModel)]="inputColor" (input)="sendInput(input.value)" /> </form> The current method involves creating a ...

Refining a JQuery scroll animation using mouseover functionality

I came across a JQuery scroll animation (inspired by this specific answer to a similar question that almost perfectly suited my requirements), and I managed to get it working. My goal is to achieve a side-scroll effect of icons when the user hovers over th ...

jQuery's feature to select all elements except one and its children appears to be malfunctioning in Safari

My goal is fairly simple. I want to make the entire section clickable, except for the span and anything beneath it, so that the link redirects elsewhere. <section id="id" class="message"> <div class="message_body"> <font color="color"> ...

What are the best practices for implementing serialization in NestJS?

Recently, I delved into a fresh NestJs project and encountered a hurdle while trying to integrate serialization. The goal was to transform objects before sending them in a network response. Initially, everything seemed to be working smoothly until I attemp ...

Code for creating a multiselect box using jQuery

Looking to create a drop-down menu with multiple checkboxes similar to this example: Are there any other sources that offer something like this? ...

Verify a different element depending on a selected input

Can anyone provide a jQuery code for validating the following HTML structure (view it on Jsbin)? HTML: <p id="options"> <strong>Options:</strong> <span> <input type="checkbox" name="ids" value="101" id="opcao-0"> <lab ...

Ensure the correct file extension is chosen when selecting a file for the 'file_field' and display any error messages using Ruby on Rails

I am currently using Ruby on Rails 3 and Prototype, and I need to be able to check the file extension when a file is selected with file_field. I only want to allow files with extensions of .doc or .pdf, any other extensions should display an error. In my ...

Retrieve all data points if both latitude and longitude are present in the XML dataset

XML data to retrieve details <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <results> <result> <Country_Code>IN</Country_Code> <Country_Name>India</Country_Name> <Region_Nam ...

Choose options from an array in AngularJS using the same ng-model for a dropdown menu

I have developed a cross-platform app using AngularJS, Monaca, and OnsenUI. Within the app, there is a large form with multiple drop-down select options. The majority of these options are Yes/No selections. To handle these Yes/No options, I've creat ...

Is there a way to shift a button within a div to the right while maintaining alignment?

After spending hours on this problem, I attempted to use "float: right" and successfully moved the button to the right. However, in doing so, the tag is no longer vertically centered. Can someone please assist me with this? Also, if there are multiple sol ...

How can the '!!user' syntax be utilized? What outcome does this code snippet produce?

I am looking to implement an angular route guard in my application. I came across this code snippet but I am confused about the line where user is mapped to !!user. Can someone explain the purpose of map(user => !!user) in this context? canActivate( ...

Changing the order of element names depending on their location within the parent element using jQuery

<div class="content"> <div> <input type="text" name="newname[name]0"/> <div> <input type="text" name="newname[utility]0"/> <div> <textarea name="newname[text]0 ...

Using jQuery to Activate Genuine Events

Is it true that jQuery's trigger() only executes event handlers bound with jQuery? I have some modules that utilize native browser event binding. Although the solution from works for me, I'm curious if there is a built-in way in jQuery to handle ...

Tips for implementing a regular expression in JavaScript to parse tags from a Docker image?

I recently came across this regex for parsing docker image tag in Python. ^(?P<repository>[\w.\-_]+((?::\d+|)(?=/[a-z0-9._-]+/[a-z0-9._-]+))|)(?:/|)(?P<image>[a-z0-9.\-_]+(?:/[a-z0-9.\-_]+|))(:(?P<tag>[\w.&bs ...

Filtering for Material Autocomplete is limited to the getOptionLabel field

Currently, I am utilizing the Google Material-UI autocomplete component. It is currently only filtering based on the "getOptionLabel" option field when text is entered into the input field. However, I would like the autocomplete to filter based on more tha ...

Retrieve the heading of a click-able element using jQuery

My challenge involves a list of selectable buttons with names generated dynamically from a JSON file. Each time a button is clicked, I aim to retrieve its title, which corresponds to row["name"]. Below is my relevant code snippet and the JSON data provided ...

Ways to access a function variable within an AJAX `done` function

This is the JavaScript function I am working with: $('.editable').change(function () { event.preventDefault(); var el_text = this.lastElementChild; var action = this.action; var method = this.method; var data = $(this).serialize(); ...

Difficulty in toggling on and off several form elements with JavaScript

Trying to control multiple form elements on an HTML page with JavaScript has presented a challenge for me. In my form, each row contains a checkbox that should enable/disable the elements on that row. The issue I'm facing is that only the first two f ...

Optimal utilization of JSON in JavaScript API: Enhancing Performance, Reinforcing Maintainability, and Optimizing Resources

Currently, I am working on developing an application using Laravel and VueJS (along with Vuex). Although I do not have much experience in working with these frameworks or front-ends, I am curious to know the best practices for utilizing the data received f ...

What is the best way to transform data from a single form into a JSON array?

explore (handlebars) {{!< main}} <form class="ui form" action="/design/add" method="POST"> <div class="order_list"&yt; <h1>Add Product</h1> <br> {{!-- <input type="f ...