Search code examples
jqueryhtmlpathname

How to use window.location to highlight the active menu item?


I'm using following code of JQuery to add a class name to the active menu item according to the URL of the menu item:

var aurl = window.location.pathname;
$('.menu li a[href="'+aurl+'"]').parent('li').addClass('active');

The problem isn't in the code itself but it's in window.location.pathname.

It works when i set the URL as the following HTML code:

<ul>
  <li><a href='/'>home</a></li>
  <li><a href='/page1'>page 1</a></li>
  <li><a href='/page%202'>page 2</li>
</ul>

But it doesn't work when i set the URL as the following HTML code:

<ul>
  <li><a href='http://myhost.com'>home</a></li>
  <li><a href='http://myhost.com/page1'>page 1</a></li>
  <li><a href='/page 2'>page 2</a></li>
  <li><a href='http://myhost.com/page 3'>page 3</a></li>
  <li><a href='http://myhost.com/page%204'>page 4</a></li>
</ul>

I need something instead window.location.pathname that can identify all these cases together.

Thank you

Update #1:

I have used 2 variables for the URL like this:

var aurl = window.location;
var burl = window.location.pathname;
$('.menu li a[href="'+aurl+'"],.menu li a[href="'+burl+'"]').parent('li').addClass('active');

It worked with all types but i still can't define the URL with space i have to replace it with %20 like:

<li><a href='/page 2'>page 2</li>

to be:

<li><a href='/page%202'>page 2</li>

Solution

  • If you want to identify both relative and absolute urls, and you want to be sure they match exactly, you will have to get the absolute url of each link and match that. As explained in this answer, the absolute url is found in the href property, independent of the type of url in the attribute.

    There is no special selector for properties (that I know of), so you could do something like this:

    var aurl = window.location.href; // Get the absolute url
    $('.menu li a').filter(function() { 
        return $(this).prop('href') === aurl;
    }).parent('li').addClass('active');