When navigating through my Razor Pages, I need to dynamically change the color of the navbar links. I attempted using JavaScript, but encountered issues with the pages getting rerendered each time, preventing me from toggling the elements.
Here's what I have experimented with:
Navbar Links
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between ml-5">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link active-link" asp-area="" asp-page="/Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" asp-area="" asp-page="/Privacy">Privacy</a>
</li>
<li class="nav-item">
<a class="nav-link" asp-page="/Movies/Index">Movies</a>
</li>
<li class="nav-item">
<a class="nav-link" asp-page="/Genres/Index">Genres</a>
</li>
</ul>
</div>
site.js
const links = document.querySelectorAll('.nav-link');
let currentActive = document.querySelector('.active-link');
const changeClass = (e) => {
//e.preventDefault();
currentActive.classList.remove('active-link');
e.target.classList.add('active-link');
};
links.forEach((el) => el.addEventListener('click', changeClass));
In this setup, I store the active link in my JavaScript file and encounter challenges when the page reloads and the script is reloaded, leading to the reset of the active link to default.
My Current Setup: https://i.sstatic.net/oZHjv.gif
Desired Output: https://i.sstatic.net/AWmKs.gif
I stumbled upon a potential solution on Stack Overflow, however, it appears to involve a workaround that feels like hard-coding. I am open to exploring better alternatives.
P.S. While a JavaScript solution would be preferred, I am flexible and open to alternative approaches.