I've been struggling to assign an "active" class to the navbar selection, but I haven't been able to get it right. I attempted using jQuery to add the class based on an example, but I'm facing difficulties in implementing it successfully. When I click on a link button like Home, the active class should be added. However, despite no console errors being found, the active class simply won't attach to the navbar links.
Here's what I have tried:
My Navbar HTML:
<nav class="navbar navbar-expand-md navbar-light bg-light sticky">
<a href="#" class="navbar-brand">
<img src="Assets/Images/spicy-food.svg" height="28" alt="SpiceFoods">
</a>
<h2 class="Nav-brand">Spice Foods</h2>
<button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#navbarCollapse">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<div class="navbar-nav ml-auto">
<a href="#" data-value="carouselIndicator" class="nav-item nav-link btn-ripple">Home</a>
<a href="#" data-value="About" class="nav-item nav-link btn-ripple">About</a>
<a href="#" data-value="Products" class="nav-item nav-link btn-ripple">Our Spices</a>
<a href="#" data-value="Contact" class="nav-item nav-link btn-ripple">Contact Us</a>
</div>
</div>
</nav>
CSS for Active Class:
.navbar-nav div>a.active {
background-color: rgba(0, 0, 0, 0.22);
font-weight: 600;
}
My jQuery Code:
$('.navbar-nav a').on('click', function () {
console.log("Click");
$('.navbar-nav').find('a.active').removeClass('active');
$(this).addClass('active');
});
If you know how to solve this issue, your help would be greatly appreciated!