Highlight Active Menu Items, What I have Used In UsmanCode

It's important to show which menu or page is currently active and which user is currently visiting. I mean that sleek effect where the "Home", "About", or "Contact" link is styled differently, showing exactly where you are. Most of us might think, "I need Razor, PHP, or some backend logic for this." But you can do it using pure JavaScript, clean and simple. This is how I have implemented it on my website.


On this website, I had a navigation bar like this:

<ul class="nav" id="main-nav">
    <li><a class="nav-link" href="/daily-tips">Daily Tips</a></li>
    <li><a class="nav-link" href="/blog">Posts</a></li>
    <li><a class="nav-link" href="/playlists">Playlists</a></li>
</ul>

The links were working fine, but there was no visual cue for users to know which page they were on. I fixed that with a small JavaScript snippet. I have placed that script just before the ending body tag i.e. </body>, and it doesn't matter if its an ASP.NET Core MVC application or any one, if it's HTML, then this solution will work. 

document.addEventListener("DOMContentLoaded", function () {
    try {
        const currentPath = window.location.pathname.toLowerCase();
        const navLinks = document.querySelectorAll("#main-nav .nav-link");

        navLinks.forEach(link => {
          const linkPath = link.getAttribute("href").toLowerCase();
          const normalize = path => path.replace(//+$/, "");

          // Remove previously added 'active' class
          link.classList.remove("active");

          // Add 'active' class if path matches
          if (
               normalize(currentPath) === normalize(linkPath) ||
               normalize(currentPath).startsWith(normalize(linkPath))
            ) {
                link.classList.add("active");
            }
        });
    } catch (err) {
        console.error("Failed to highlight active menu item:", err);
    }
});


The above script will add the .active class to the menu nav link, and to see the menu highlighted, I have added a CSS class :

.nav-link.active {
    font-weight: bold;
    color: #007bff;
    border-bottom: 2px solid #007bff;
}

This gives the active link a bold look with a nice blue underline. That was all for this tip. Until the next time, say curious and keep coding.