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>