jenhan
jenhan

Reputation: 829

jQuery function to add active class highlights more than one link

I'm using this function to add an active class to the links in my main nav:

$(function() {
  $('nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');
});

Most of the links point to an index.php file within a directory. So the structure is set up like this:

  <nav class="nav-collapse">
    <ul>
      <li><a href="/index.php" id="nav-home">HOME</a></li>
      <li><a href="/company/index.php" id="nav-company">OUR COMPANY</a></li>
      <li><a href="/services/index.php" id="nav-services">OUR SERVICES</a></li>
      <li><a href="/partners/index.php" id="nav-partners">OUR PARTNERS</a></li>
    </ul>
  </nav>

The problem I'm having is that when I initially go to the site, all three are highlighted. If I click on the logo to refresh, only the "home" link is highlighted. Any way to fix this?

Upvotes: 0

Views: 75

Answers (1)

tymeJV
tymeJV

Reputation: 104795

Im guessing on the initial load, the location path doesn't have a value, so just give it a default:

var path = location.pathname.split("/")[1];

if (path == "") path = "index.php";

$('nav a[href^="/' + path + '"]').addClass('active');

Upvotes: 1

Related Questions