Changing the li tag by clicking on it is a simple task that can be easily

Whenever I click on a tag, I want the li class to change to "active" and open a new page with the corresponding tag as active. For example, if I click on the Overview tag, the new page should open with the li tag as active. I have attempted to write some code to achieve this, but I have been unsuccessful in changing the active status of the li element.

Below are the code snippets I have used.

Home Page

<div class="col-sm-3 col-md-2 sidebar">
    <ul class="nav nav-sidebar">
        <li class="active"><a href="index.jsp">Overview</a></li>
        <li><a href="list_users">Users</a></li>
        <li><a href="#">Categories</a></li>
        <li><a href="#">Books</a></li>
    </ul>
        <ul class="nav nav-sidebar">
        <li><a href="#">Customers</a></li>
        <li><a href="#">Reviews</a></li>
        <li><a href="#">Orders</a></li>
        </ul>
</div>

User Page.

<div class="col-sm-3 col-md-2 sidebar">
    <ul class="nav nav-sidebar">
        <li><a href="index.jsp">Overview</a></li>
        <li><a href="list_users">Users</a></li>
        <li><a href="#">Categories</a></li>
        <li><a href="#">Books</a></li>
    </ul>
    <ul class="nav nav-sidebar">
        <li><a href="">Customers</a></li>
        <li><a href="">Reviews</a></li>
        <li><a href="">Orders</a></li>
    </ul>
</div>

Javascript code

<script>
    // Nav bar change active status
    $(".nav li").on("click", function() {
        $(".nav li").removeClass("active");
        $(this).addClass("active");
    });
</script>

The issue I am facing is that the Javascript code is not working as expected. When I click on any item, the active status of the li does not change.

On the Home Page, it should normally display like this:

<div class="col-sm-3 col-md-2 sidebar">
    <ul class="nav nav-sidebar">
        <li><a href="index.jsp">Overview</a></li>
        <li class="active"><a href="list_users">Users</a></li>
        <li><a href="#">Categories</a></li>
        <li><a href="#">Books</a></li>
    </ul>
    <ul class="nav nav-sidebar">
        <li><a href="">Customers</a></li>
        <li><a href="">Reviews</a></li>
        <li><a href="">Orders</a></li>
    </ul>
</div>

But currently, it actually appears like this:

<div class="col-sm-3 col-md-2 sidebar">
    <ul class="nav nav-sidebar">
        <li><a href="index.jsp">Overview</a></li>
        <li><a href="list_users">Users</a></li>
        <li><a href="#">Categories</a></li>
        <li><a href="#">Books</a></li>
    </ul>
    <ul class="nav nav-sidebar">
        <li><a href="">Customers</a></li>
        <li><a href="">Reviews</a></li>
        <li><a href="">Orders</a></li>
    </ul>
</div>

.nav-sidebar > .active > a,
.nav-sidebar > .active > a:hover,
.nav-sidebar > .active > a:focus {
  color: #fff;
  background-color: #428bca;
}

I am seeking help to resolve the issue with the Javascript code not working as expected. How can I fix this problem?

Answer №1

Have you considered using the CSS pseudo class :active as a potential solution?

.nav li:active {
    // customize your style here
}

Answer №2

My solution is ready and here it is.

$(function(){
  var current_page_URL = location.href;
  $( "a" ).each(function() {
     if ($(this).attr("href") !== "#") {
       var target_URL = $(this).prop("href");
       if (target_URL == current_page_URL) {
          $('nav a').parents('li, ul').removeClass('active');
          $(this).parent('li').addClass('active');
          return false;
       }
     }
  });
});

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

Building a local database using the MVC framework concept

Can a locally stored database be developed using MVC framework principles in javascript and html5? Thank you Ravindran ...

Implementing Multiple Identification using JavaScript and PHP

I need to complete a simple task. Here is the code snippet: echo' <div class="col-sm-12" id="recensioni_titolo"> <form role="form" id="review-form" method="post" action="php\insert_comment.php"> ...

modify header when button is clicked

I am trying to create a JavaScript function that will update the name of an HTML table header when a button is clicked. However, I am having trouble accessing the text content within the th element. document.getElementById("id").text and document.getEl ...

Discover a class located following a specific element even when they are not directly related

There is a group of elements all with the class month. Some of them also have the class cal, while only one has the class today. The goal is to locate the first element with the class cal, but only after finding the element with the class today. The chall ...

What could potentially be the reason behind the incapability of the next.js Image component to transform the svg into a

Unique Context I recently developed a minimalist Hero + Navbar using Next.js. The site utilizes the powerful next.js Image component to display images. Surprisingly, all three images on the website, which are in .webp format, load instantly with a size of ...

Issue with child prop not being updated despite changes in parent component

I'm facing a strange issue where altering a child component's prop doesn't trigger a re-render. Here's the scenario: In the parent component, I have: <child :problemProp="proplemPropValue"></child> In the child component, ...

Passing event handlers to Client Components within NextJS 13 and using the <button onClick={}> element is not supported

Oops! It looks like you can't pass event handlers to Client Component props. If you want your component to be interactive, consider converting some of it to a Client Component. const reqHelp = () => { Swal.fire({ title: '1', ...

Ensure prototype is easily accessible within vuex

Within my app.js file, I implemented a functionality to enable translation in Vue: Vue.prototype.trans = string => _.get(window.i18n, string); This feature works perfectly when used in my Vue files: {{ trans('translation.name') }} However, ...

Twice the fetch is triggered

I've implemented a simple JavaScript function that handles fetching a URL and updating the HTML page upon receiving a response. Here's an example of how it works: function postToDatabase(self) { // other code here async function postData() ...

Discovering if an agent is a mobile device in Next.js

I am currently working with nextjs version 10.1.3. Below is the function I am using: import React, {useEffect, useState} from "react"; const useCheckMobileScreen = () => { if (typeof window !== "undefined"){ const [widt ...

Obtain the inner text input value using jQuery

In my form, there is a feature that adds a new row of text inputs dynamically when a user wants to add more rows. Each new row is automatically populated with input fields that have the same id and class as the previous ones. My question is: how can I re ...

What is the best way to retrieve a list of customers within a specified date range?

How can I retrieve a list of customers within a specified date range? My frontend react app includes starting and ending date pickers, but I'm unsure how to query the data using mongoose in my express app. Below you'll find my mongoose model and ...

Executing a function with arguments within a separate function

I've been working on creating a scheduler function that can randomly call another function with parameters. Here's the JavaScript code I have so far: function scheduleFunction(t, deltaT, functionName) { var timeout; var timeoutID; ...

Issues with rotating the camera in three.js are causing functionality problems

I have been working on a code snippet to rotate my camera around the x-axis within a three.js environment: var cameraOrginX = 0, cameraOrginY = 0, cameraOrginZ = 0; var cameraEndX = 0, cameraEndY = 0, cameraEndZ = 1000; var angle = 0; function initialize ...

When using `npm publish`, any files located within the `node_modules

After developing an npm package, I included some modules in the node_modules directory to make them accessible as "modules". For instance, I have a module called my-module.js in node_modules which I require in my code using require('my-module'). ...

How can I set up Emacs company-bootstrap to automatically activate in web-mode?

While working in web-mode and editing an html file, I find myself needing to use M-x company-bootstrap to display a list of possible values for a class in an html tag. <p class="M-X company-bootstrap here .."> Is there a way to automatical ...

Configure WebStorm so that node_modules is set as the library root, while simultaneously excluding it from indexing

Can WebStorm projects be configured to set the node_modules as the library root, while also excluding it from indexing? I thought I saw a project that had node_modules marked as both library root and excluded, but I'm unsure how to do this. Does anyo ...

What is the best way to fulfill a promise after a CSV file has finished being read?

I have been utilizing the 'fast-csv' module that can be found at this link (https://www.npmjs.org/package/fast-csv), but I am open to switching to a different one. I attempted promised-csv (https://www.npmjs.org/package/promised-csv) but I had tr ...

How can data be transferred from a parent component to a child component using MaterialUI's styling functionality?

Recently delving into the world of reactjs, I've been tinkering with a basic page that incorporates authentication using state. To spruce up the design, I decided to use the MaterialUI framework. The issue I'm facing is related to sending the lo ...

Learn how to send data from a MySQL server to a Node.js application using Socket.IO

I've been facing a challenge recently. I am attempting to listen for events from the @rodrigogs/my-sql events node package and then emit those events through socket-io to the react client. However, there seems to be a disconnect that I can't see ...