简体   繁体   中英

Adding active class to current page in nav with jQuery

I'm trying to add the 'active' class to the current page's nav link in the header. I made some progress, but I'm running into a small bug, and would appreciate some help. I know the answer is quite obvious, however, I'm new to jQuery/Javascript and I'm having trouble finding it on my own.

Here's my nav HTML structure:

<nav class="navbar navbar-expand-lg navbar-dark fixed-top" id="nav">
      <ul class="navbar-nav ml-auto">
        <li class="nav-item">
          <a href="/" class="nav-link">Me</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="/work">Work</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="/play">Play</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="/contact">Contact</a>
        </li>
      </ul>
</nav>

Simple enough. Here's the jQuery code:

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

The code works on inner pages, however, I'm running into an issue wherein on the home page ('Me', href="/"), the code is adding the active class to all of the nav links.

I think the problem would be solved if I used href="/work/" (added a / to the end of all links), however, when I do that, the links no longer work, because the site then tries to go to www.sitename.com/work/.php.

This is either a simple .htaccess or jQuery fix, however I'm not sure which one, or how to implement it.

Thanks!

That's happening because you are using the ^= selector. That means 'startWith' so since all urls start with '/' the 'active' class is being added to all of them.

Replace it with the equal selector and it should work.

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

A simpler approach is compare the href property of link to page url

$('nav li a').filter(function(){
  return this.href === location.href;
}).addClass('active');

Although the href attribute only contains a path, the href property in the DOM contains the full url

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM