Change active navbar link using JavaScript in ASP.NET Core Razor Pages

I need to change the navbar link color when I’m navigating through my Razor-Pages. I tried to use JavaScript, but it seems that the pages are getting rerendered every time when I go to another page and I’m not able to toggle my elements.

Here is what I have tried so far:

Nav bar 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 class="nav-item">
                        <a class="nav-link" asp-area="" asp-page="/Privacy">Privacy</a>
                    <li class="nav-item">
                        <a class="nav-link" asp-page="/Movies/Index">Movies</a>
                    <li class="nav-item">
                        <a class="nav-link" asp-page="/Genres/Index">Genres</a>


const links = document.querySelectorAll('.nav-link');
let currentActive = document.querySelector('.active-link');

const changeClass = (e) => {

links.forEach((el) => el.addEventListener('click', changeClass));

Here I save the current active link in my js and when I navigate to another page, the page gets rerendered and my js file is reloaded again so that the value that I have previously is set back to the default active link.

What I have: current

What I want: desired

I found one possible solution, but it seems to be a bit of hard-coding and working around, I believe there should be a better way.

P.S. Ideally, a solution using JavaScript would be best, however, I’m not sticking to anything here.


Use the DOMContentLoaded event rather than the click event. That way the change will be applied to the actual page after it has rendered. At the moment, you are applying the change to the links on the page that you are navigating from:

document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('.nav-link').forEach(link => {
        if (link.getAttribute('href').toLowerCase() === location.pathname.toLowerCase()) {
        } else {