In my web application, I have a navbar that navigates to different pages.
<nav class="navbar navbar-expand-md sticky-top navbar-ligth bg-fadded">
<a class="nav-link waves-effect waves-light" th:href="@{/}">
<img class="home-logo" alt="UTL-2" th:src="@{/static/img/site-logo.png}"/></a>
<div class="collapse navbar-collapse justify-content-center" id="navbarSupportedContent">
<ul id="myDIV" class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link waves-effect waves-light" th:href="@{/login}">Login
<span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link waves-effect waves-light" th:href="@{/plan}">Plan</a>
</li>
<li class="nav-item">
<a class="nav-link waves-effect waves-light" th:href="@{/orders}">Orders</a>
</li>
<li class="nav-item">
<a class="nav-link waves-effect waves-light" th:href="@{/stations}">Stations</a>
</li>
<li class="nav-item">
<a class="nav-link waves-effect waves-light" th:href="@{/partner}">Partners</a>
</li>
<li class="nav-item">
<a class="nav-link waves-effect waves-light" th:href="@{/map}">Map</a>
</li>
<li class="nav-item">
<a class="nav-link waves-effect waves-light" th:href="@{/info}">Info</a>
</li>
</ul>
</div>
</nav>
To apply the "active" class to a nav-item when clicked, I use this simple script:
<script>
var btnContainer = document.getElementById("myDIV");
var btns = btnContainer.getElementsByClassName("nav-item");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
if (current.length > 0) {
current[0].className = current[0].className.replace(" active", "");
}
this.className += " active";
});
}
</script>
While this script works on static pages, when navigating to another page the element loses the "active" class. Is there a way to only update the body of the webpage or mark elements differently? How does this work in Bootstrap?
I found a solution using Thymeleaf, but how can I retrieve the current active link: th:classappend="${module == 'login' ? 'active' : ''}" What is the correct element that can return the current link?