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?