I have a basic side menu structure which is generated dynamically based on post topics. Using the code below I am able to individually highlight the active link as intended when viewing the individual topic page. However, on the main or index page that lists all topics, every anchor element in the side nav is given an 'active' class. How can I prevent the index page sidenav anchors from receiving 'active' classes while retaining the 'active' class on individual topic pages?
Thanks in advance to anyone whom can provide some insight...
Side nav structure:
<div class="sidenav">
<ul>
<li><a href="//example.com/customer/topic/government">Government</a></li>
<li><a href="//example.com/customer/topic/hospitality">Hospitality</a></li>
<li><a href="//example.com/customer/topic/industrial">Industrial</a></li>
</ul>
</div>
Javascript:
$(function(){
var current = location.pathname;
$('.sidenav li a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
})
})
Current output using above JS on individual topic pages:
<div class="sidenav">
<ul>
<li><a href="//example.com/customer/topic/government">Government</a></li>
<li><a href="//example.com/customer/topic/hospitality" class="active">Hospitality</a></li>
<li><a href="//example.com/customer/topic/industrial">Industrial</a></li>
</ul>
</div>
Current output using above JS on topic index page (/customer)
<div class="sidenav">
<ul>
<li><a href="//example.com/customer/topic/government" class="active">Government</a></li>
<li><a href="//example.com/customer/topic/hospitality" class="active">Hospitality</a></li>
<li><a href="//example.com/customer/topic/industrial" class="active">Industrial</a></li>
</ul>
</div>