Issue with Bootstrap 4 .active class not updating after click

In my ASP.NET MVC core website, I am utilizing bootstrap v4.3.1. The navbar has the .active class on the first li tag:

<nav class="navbar navbar-expand-md navbar-toggleable-md navbar-dark bg-navbar fixed-top mb-3">
  <div class="container">
    <a
      class="navbar-brand"
      asp-area=""
      asp-controller="Home"
      asp-action="Index"
    >
      <img id="nav-logo" src="~/Images/LOGO's.png" alt="G&Z Installation" />
    </a>
    <button
      class="navbar-toggler"
      type="button"
      data-toggle="collapse"
      data-target=".navbar-collapse"
      aria-controls="navbarSupportedContent"
      aria-expanded="false"
      aria-label="Toggle navigation"
    >
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="navbar-collapse collapse d-md-inline-flex flex-md-row-reverse">
      <ul class="nav ml-auto">
        <li class="nav-item">
          <a
            class="nav-link active text-light nav-text"
            asp-area=""
            asp-controller="Home"
            asp-action="Index"
          >
            Home
          </a>
        </li>
        
        <!-- Other li items here -->
        
      </ul>
    </div>
  </div>
</nav>;

I have added this code for functionality:

$(document).ready(function () {
  $("a.nav-link.text-light.nav-text").on("click", function () {
    $(".nav").find(".active").removeClass("active");
    $(this).addClass("active");
  });
});

However, despite the code being in place, the active class does not switch to other li items when clicked. It remains on the first li item. Bootstrap is included in the head of the layout page:

<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />

The scripts are loaded at the bottom of the layout page:

<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>

Upon inspecting the elements in the browser, the active class seems to be removed and re-added when a different li item is clicked. Adjusting the JavaScript code to target the li item instead of the a tag resolves the issue but breaks the navigation functionality. Any guidance on what might be going wrong?

Answer №1

To implement this feature, you can follow the code snippet below. This uses an active class in CSS for demonstration purposes, but feel free to customize it as needed. Thank you!

$(document).ready(function () {
$("a.nav-link").on("click", function () {
$("a.nav-link").each(function(i,o)
{
$(this).removeClass("active");
});
    $(this).addClass("active");
})
});
.active {
  background-color: #666;
  color: white;
}
<html>
<head>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>

<nav class="navbar navbar-expand-md navbar-toggleable-md navbar-dark bg-navbar fixed-top mb-3">
        <div class="container">
            <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">
                <img id="nav-logo" src="~/Images/LOGO's.png" alt="G&Z Installation" />
            </a>
             <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse"
                    aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="navbar-collapse collapse d-md-inline-flex flex-md-row-reverse">
                <ul class="nav ml-auto">
                    <li class="nav-item">
                        <a class="nav-link active text-light nav-text" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-light nav-text" asp-area="" asp-controller="Home" asp-action="SolarPanels">Zonnepanelen</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-light nav-text" asp-area="" asp-controller="Home" asp-action="AircoAndHeatPump">Airco & Warmtepomp</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-light nav-text" asp-area="" asp-controller="Home" asp-action="Contact">Contact</a>
                    </li>
                    
                </ul>
            </div>
        </div>
    </nav>
    </body>
    </html>

Answer №2

Special thanks to Jon's solution on this thread for helping me out!!! :D I made a tweak in the JS code like so:

$(document).ready(function() {
  $('li.active').removeClass('active');
  $('a[href="' + location.pathname + '"]').closest('li').addClass('active'); 
});

Everything is working perfectly now :)

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

Steps to create a scrollable material-ui Modal

After setting up a Modal, I encountered an issue where the text describing my app inside the modal was overflowing, making it impossible to see the top and bottom parts. To solve this problem, I want to implement scroll functionality within the component s ...

What is the method for inserting the document URL into a text input?

Can someone provide guidance on grabbing the top URL and inserting it into a text input field? I've tried the following method, but it's not working. Any suggestions or ideas? Additionally, is there a way to make this text input field uneditable? ...

When we need to select the button with identical class and name attributes and click to activate it

Is there a way to click a button with the same class name and name attribute as another element without using the xpath method? input class="btnstyle greenbtn paddinglr20" type="submit" value="Upload " name="submit_upload I attempted this for the second ...

delete the final directory from a file directory

let currentLocation = window.location.pathname; let directory = currentLocation.substring(0, currentLocation.lastIndexOf('/')); The current location is: /examples/html/home/ The directory is: /examples/html/home I am trying to remove the las ...

The tag <li> is not allowing enough room for the content to expand as needed

I am trying to create a list using ul li elements. When the content inside the li exceeds the width, a scrollbar appears. However, I am encountering an issue where the li tag does not cover the entire width and spills outside. .container{ b ...

Manipulating divs by positioning them at the top, left, right, bottom, and center to occupy the entire visible portion of the page

Many suggest avoiding the use of table layouts and opting for divs and CSS instead, which I am happy to embrace. Please forgive me for asking a basic question. I am looking to create a layout where the center content stretches out to cover the entire visi ...

What is the best way to align text in "reverse order" to the center?

While utilizing text-align: center, I noticed that the remainder remains at the end. Here is how it currently looks: https://i.sstatic.net/DjQU4.png However, I am seeking to achieve this effect where the remainder remains at the start: https://i.sstatic ...

Is there an issue with the jQuery ajax function when it comes to sending the RegistrationId to our server?

Beginning to work with the pushNotification service for my Android app, I successfully received a registration ID from the GCM server and attempted to send this ID to our server using a jQuery AJAX function. My intention was to send this ID after the user ...

Modify HTML table cell colors based on their values

Hey there, I'm currently working on a project where I need to dynamically change the colors of an HTML table based on values retrieved from a database. To give you a better idea, here is an image showcasing what I am trying to accomplish. https://i.ss ...

jQuery Triggered Download Resulting in 'Error: Connection Issue'

I need to trigger a download using a JQuery AJAX request once it's finished. EXAMPLE CODE: $('.getPDF').click(function(){ var filepath = 'localhost:3000/pdf/formula-' + this.id + '.pdf'; $.ajax({ url: '/formu ...

What is the best way to improve the design of this division that includes buttons?

I'm having trouble with the layout of three divs I have set up. One acts as a container, while the other two are meant to hold buttons. However, something seems off and I can't figure out how to correct it. .button { display: inline-block; ...

Validation of forms in Angular using a pseudo submission method

On a webpage, there is a form with two buttons: one to calculate a price and the other to submit the form. Below is a basic example: <form novalidate name="formStep1"> <select ng-model="address" required> <option></option> ...

Clicking on the button will reset the counter

I have a code snippet that counts down from 15 and displays "times over" after 15 seconds have passed. The issue arises when a user clicks the button multiple times, resulting in multiple countdowns appearing in the same Div. I am looking for a way to rese ...

How can I create a hyperlink that leads to multiple pages?

I am looking to create a hyperlink that will lead to a random webpage each time it is clicked from a selection of URLs. Can anyone suggest a suitable function to get started on this task? ...

Editable JSON data within a table using Twitter Bootstrap

How come I am unable to utilize the bootstrap editable table in this manner? <table id="addElements" data-height="299"> <thead> <tr> <th data-field="id" data-align="right">Item ID</th> < ...

Is it beneficial to use both Bootstrap and ng-bootstrap together?

I have two modules in my angular website - "bootstrap" and "ng-bootstrap". Do I need both or just one? I am thinking of keeping only "ng-bootstrap" 4.0.0.0 and removing "bootstrap". Is this acceptable? What are the steps to remove "Bootstrap"? Can I simp ...

JavaScript program failing to execute

Seeking to incorporate a read more and read less feature that activates on click for my articles application using Django. However, encountering an issue where my JavaScript code does not work when the read more link is clicked. Below are the relevant fil ...

Running Controllers from Other Controllers in AngularJS: A Guide

Switching from a jquery mindset to Angular can be challenging for beginners. After reading various tutorials and guides, I am attempting to enhance my skills by developing a customizable dashboard application. Here is the HTML I have so far: <div ...

Angular ui-router redirection without altering the ui-view contents

Here's the code snippet from my app.js: // Setting up states using $stateProvider $stateProvider .state('/', { url: "/", views: { "top": { temp ...

Display only the spans that contain text or are not empty

I need a solution to hide only those spans that are empty. <div class="img-wrapper"> <div class="showcase-caption" style="display: block; "> <span id="MainContent_ImageCaption_0">This one has caption</span> </div> ...