0

I am trying to add an active class to li based on the active URL, This what I got, unfortunately, it is not working when the

<li class="scroll"><a href="index.php">Home</a></li>

and it will work when :

<li class="scroll"><a href="">Home</a></li>

The jQuery is:

jQuery(function($) {
     var path = window.location.href;
     if ( path == '' ) {
       path = 'index.php';
     }
     $('ul li a').each(function() {
      if (this.href === path) {
       $(this).parent().addClass('is-current');
      }
     });
    });

Thank you!

talElm
  • 5
  • 3

2 Answers2

0

This is because window.location.href returns the full url, meaning something like

www.example.com/folder/index.php

Perhaps this could help you, as you would only need the file name.

PaulS
  • 850
  • 3
  • 17
0

The reason this is happening is that the URL will not be mysite.com/index.php

You need to have your active state based on the URL path.

https://developer.mozilla.org/en-US/docs/Web/API/Location

window.location.pathname is what you are looking for. That will return the end of the URL with a leading / and you can base your check on that string.

If you are on the base URL (usually the home page), the check won't contain a path and if you're on a sub page of the domain you can then check for instance:

// site.com/about
const path = window.location.pathname

if (path === '/about') {
  $('li').addClass('active')
}
Josh Kelly
  • 938
  • 5
  • 12
  • Thank you! jQuery(function($) { var path = window.location.pathname; if ( path == '' ) { path = 'index.php'; } $('ul li a').each(function() { if (this.pathname === path) { $(this).parent().addClass('is-current'); } }); }); – talElm Jan 30 '20 at 14:23