I have been attempting various approaches to change the active class on a Bootstrap navbar (in Bootstrap 4), but I am facing difficulties. Each time I click on a new menu option, it momentarily changes to the active class before reverting back to 'home' being active.
Below is my navbar:
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="{% url 'home' %}">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/blog">Blog</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
<li class="nav-item btn-group">
<a class="nav-link dropdown-toggle" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Deals
</a>
<div class="dropdown-menu dropdown-primary" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
</ul>
This is my javascript code:
<script>
$(".navbar-nav li").on("click", function(){
$(".navbar-nav li").removeClass("active");
$(this).addClass("active");
});
</script>