0

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>
Community
  • 1
  • 1
Ken
  • 368
  • 3
  • 11

1 Answers1

2

Try this added the last key to current might be a protocol issue this way you can be always sure

$(function(){
    var current = location.pathname;
    current = current.substring(current.lastIndexOf('/'));
    $('.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');
        }
    });
});
joyBlanks
  • 6,419
  • 1
  • 22
  • 47
  • thanks for the help! Still encountering the same issue, where .active is added to all anchors on the /customers page. I thought maybe I could look for /customers/topic using lastIndexOf, but the issue persists. The behavior on individual topic pages is correct in that only active class is added to the anchor that's currently being viewed. – Ken Aug 14 '15 at 02:26