This simple script adds an "active" class to a link in a list when page's url is = link's href attribute
var TheP = window.location.pathname.split('/');
var HeRe = TheP[TheP.length-1];
$('ul a').each(function(){
var Link = $(this).attr('href');
if (Link == HeRe){ $(this).addClass('active');}
});
And it works. But ... only when the href attribute is just a single file href="index.html"
. Doesn't work at all in these next cases or similar:
<a href="foo/index.html">foo</a>
<a href="../bar/index.html">bar</a>
Actually to solve it I could write:
var TheP = window.location.pathname.split('/');
var P1 = TheP[TheP.length-1];
var P2 = TheP[TheP.length-2];
var HeRe = P2+"/"+P1;
$('ul a').each(function(){
var Ln = $(this).attr('href');
var Ln = Ln.split('/');
var L1 = Ln[Ln.length-1];
var L2 = Ln[Ln.length-2];
var Link = L2+"/"+L1;
if (Link == HeRe){$(this).addClass('active');}
});
But ... ehm ... I think there should be a better and more flexible way. Also because what is above doesn't work having just a single file as path : (