I have a menu that uses the following jQuery to add the class active to highlight the current page.
<script>
jQuery(document).ready(function($) {
$(function() {
setNavigation();
});
function setNavigation() {
var path = window.location.pathname;
path = path.replace(/\/$/, "");
path = decodeURIComponent(path);
$(".nav a").each(function() {
var href = $(this).attr('href');
if (path.substring(0, href.length) === href) {
$(this).closest('li').addClass('active');
}
});
}
});
</script>
This is my HTML:
<ul class="nav">
<li><a href="/wordpress">Portfolio One</a></li>
<li><a href="/wordpress/portfolio-two">Portfolio Two</a></li>
<li><a href="/wordpress/portfolio-three">Portfolio Three</a></li>
<li><a href="/wordpress/bio-contact">Bio / Contact</a></li>
</ul>
As you can see the first link (Portfolio One) Links to the main page. This is causing that this link always has the class active regardless what page the menu is on.
Can anyone provide some insight into amending my jQuery so it gets the full link and excludes only partial matches?
The reason your links in the menu always have an active class is because it's not being removed for inactive links. you can try adding
$('.nav li').removeClass('active');
this will first remove theactive
class and then you can add the active class for the current active link.here's the updated code.