Dan Mitchell
Dan Mitchell

Reputation: 864

Add active class to parent nav when on child pages

I need to highlight the parent nav item when a user is within a child page based on the URL.

User is currently on the page foo1-child and the parent is foo1 so I need to add the active class to Foo 1: http://foo.com/foo1/foo1-child.html

NAV:

<ul class="main-nav">
  <li><a href="/foo.com/foo1.html">Foo 1</a></li>
  <li><a href="/foo.com/foo5.html">Foo 5</a></li>
</ul>

I have no issue adding an active class to links within the nav as I just compare every the href in the .nav li a vs the URL but how can I check the URL for a matching anchor link name in the URL or something similar?

Current JS

  $('.main-nav li > a').each(function () {
    var $this = $(this);
    if ($this.attr('href').indexOf(location.pathname) !== -1) {
      $this.addClass('active');
    }
  });

Upvotes: 3

Views: 2680

Answers (1)

Gavriel
Gavriel

Reputation: 19237

If you cut off the ".html" from the end of both of them and you search for the a's href (which should be shorter) in the location, it should work.

  $('.main-nav li > a').each(function () {
    var $this = $(this);
    var loc = location.
    if (location.pathname.replace(/\/[^\/]*\.html$/, '').startsWith($this.attr('href').replace(/\.html$/, ''))) {
      $this.parent().addClass('active');
    }
  });

You can see it in "action" here: https://jsfiddle.net/c8u2f91v/ Note it uses a fake location_pathname instead of location.pathname, because jsfiddle doesn't have the necessary prefixes in the path, but it shows that it should work.

Upvotes: 2

Related Questions