Add Active Navigation Class Based on URL

Add Active Navigation Class Based on URL

Let’s take an example.

You have a menu something like this:

<nav>
  <ul>
    <li><a href="/">Home</a></li>
    <li><a href="/about/">About</a></li>
    <li><a href="/clients/">Clients</a></li>
    <li><a href="/contact/">Contact Us</a></li>
  </ul>
</nav>

and you are on the About page where your URL is: https://yoursitename.com/about

Write the following Jquery to display active menu.

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

Jquery find the active page URL and add the active class to the <a> tag.