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

Critical bug discovered in fundamental Vue.js component by Internet Explorer

My Vue.js-powered application is performing flawlessly in all web browsers, except for one... Upon attempting to launch it on Internet Explorer, a frustrating error appears: An anticipated identifier in vue.min.js, line 6 character 4872 Locating the spe ...

Finding the value of a span tag using a specific CSS class with jQuery

How can I retrieve the value of a span tag based on its css class using jQuery? <span class="page-numbers current">3</span> I attempted to do so with the following code: var pageno = $(".page-numbers current").val(); alert(pageno); Howeve ...

How to centrally align grids in a material-ui react application

I'm trying to center Grid items horizontally inside a Grid container, while also adding some spacing between the items. Here's the code I have so far: import React from "react"; import { makeStyles } from "@material-ui/core/styles& ...

Struggling to close modal popup after submitting form

click here for imageCurrently, I am working with the bootstrap modal plugin to create an inquiry form. The issue I am facing is that even though I am using the "ng-submit" directive to save the form details, when I click submit, the form submits successful ...

CSS resetting can lead to tables appearing misaligned

After applying a CSS reset to my website's stylesheet (which is valid as CSS 2.0 and used with XHTML 1.0 transitional webpage), I noticed that a table on my website no longer looks correct. Specifically, the table is now positioned incorrectly and the ...

validation for grouped radio inputs

I'm having a small issue with appending error states. I have 7 radio inputs and after submitting, I see 7 error states under the group. Can someone assist me in modifying the code? <form class="register-form"> <div class="co ...

Tips for executing a jQuery function on multiple sets of elements

Currently, I have a list with all items sharing the same class name. There is a jQuery plugin that identifies the tallest element and sets the height of all list items to match the tallest one. My goal is to run this method for each UL group individually. ...

Using ThreeJS to load and display several meshes from a .json 3D file

I downloaded a .json file from an online 3D editor and now I'm facing an issue while trying to load and create 20 instances of it, similar to this example. Sadly, my code seems to be flawed as all 20 instances are behaving as if they are the same obje ...

angular5: The ngFor directive will only function properly after the second button click

Here is my current situation: 1) When the user inputs a keyword in a text field and clicks on the search icon, it triggers an HTTP request to retrieve the data. 2) The retrieved data is then rendered in HTML using ngFor. The issue I am facing is that up ...

Strategies for Efficiently Caching AJAX Responses to Minimize Further HTTP Requests

Recently, I implemented a tabbed-layout on my website where each tab leads to a different page. However, I am looking for a way to prevent a new HTTP post call every time the user switches between tabs. Ideally, I would like to find a JS-based solution t ...

Guide on navigating to a different page following a successful Google Sign In within React18

I'm facing an issue with redirection after signing in with Google on my React 18 project. Despite successfully logging in, the page does not redirect as expected. Below is a snippet of my Login.jsx file where the Google login functionality is implemen ...

JavaScript: What is the concept of overriding function named params?

function retrieveData({item1 = "blue", item2 = 7}) { console.log('theItems'); console.log(item1); console.log(item2); } retrieveData( { item1: 'pink', item2: 9 } ); I've come across conflicting i ...

encountering a type mismatch error while trying to retrieve data from an array

While attempting to retrieve data from a nested array, I encountered the error "TypeError: Cannot read property 'value' of undefined". It seems like I might be calling back incorrectly as I am receiving both the output and the error message in th ...

The ultimate guide to loading multiple YAML files simultaneously in JavaScript

A Ruby script was created to split a large YAML file named travel.yaml, which includes a list of country keys and information, into individual files for each country. data = YAML.load(File.read('./src/constants/travel.yaml')) data.fetch('co ...

Which is the Better Choice for an MMO WebSocket Server: Node.js or C++?

Contemplating creating a live game using WebSockets for the web has been on my mind. With my knowledge of Node.js, it's tempting to develop it there. However, C++ appears to be the favored server language due to its speed. Would it be best to try bui ...

using an array as an argument in the filtering function

Is there a way to pass an array to the filter method in JavaScript? I have successfully filtered an array using another array. However, my filter array currently has a global scope. How can I pass the array to make my code cleaner? var array = [1, 2, 3, ...

Determine whether there is greater available space above or below a specific element within the DOM

I'm looking to create a dynamic layout where an input field is accompanied by a list in a div, positioned either above or below depending on available space. This setup needs to account for the fact that the input field could be located anywhere on th ...

Tips for effectively resizing an iframe within a grid layout

Task Tailwind React When adjusting the scale of an iframe, it disrupts its position within the grid. Expected Outcome: The iframe should maintain its position after scaling, but with a smaller size. Current Behavior: The iframe's position is be ...

The source 'http://localhost:3000' is not authorized to access the Twitter API

I am working on a web application that utilizes the Twitter API REST. On one of my pages, I have a list of Twitter accounts and a button to add a new account. When this button is clicked, it triggers a function in the Angular controller: // Function to ...

Guide on displaying the name attribute of a button along with its price in a separate div when clicked

Upon clicking the Koala button, I want to display a message showing the id name of the button and the corresponding price for Koalas. Here is the HTML code snippet: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <link h ...