I'm trying to add the 'active' class to the current page's nav link in the header. I made some progress, but I'm running into a small bug, and would appreciate some help. I know the answer is quite obvious, however, I'm new to jQuery/Javascript and I'm having trouble finding it on my own.
Here's my nav HTML structure:
<nav class="navbar navbar-expand-lg navbar-dark fixed-top" id="nav">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a href="/" class="nav-link">Me</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/work">Work</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/play">Play</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/contact">Contact</a>
</li>
</ul>
</nav>
Simple enough. Here's the jQuery code:
$(function() {
$('nav li a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');
});
The code works on inner pages, however, I'm running into an issue wherein on the home page ('Me', href="/"), the code is adding the active class to all of the nav links.
I think the problem would be solved if I used href="/work/" (added a / to the end of all links), however, when I do that, the links no longer work, because the site then tries to go to www.sitename.com/work/.php.
This is either a simple .htaccess or jQuery fix, however I'm not sure which one, or how to implement it.
Thanks!