Adding active class to current page in nav with jQ

2020-08-01 18:56发布


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 class="nav-item">
          <a class="nav-link" href="/work">Work</a>
        <li class="nav-item">
          <a class="nav-link" href="/play">Play</a>
        <li class="nav-item">
          <a class="nav-link" href="/contact">Contact</a>

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

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



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;

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