Reputation: 149
I am adding a class to the link to the current page using the following code:
var pathname = window.location.pathname;
$("ul#inventory-categories a").each( function() {
var href= $(this).attr("href");
if (href.length && pathname.indexOf(href) >= 0){
$(this).addClass("active");
}
});
This works fine for relative links but not absolute links.
Can anyone offer any insight?
Upvotes: 0
Views: 70
Reputation: 1001
var pathname = window.location.href;
$("ul#inventory-categories a").each( function() {
var href= $(this).attr("href");
if (href.length && pathname.indexOf(href) >= 0){
$(this).addClass("active");
}
});
or...
var pathname = window.location.pathname;
var url = window.location.href;
$("ul#inventory-categories a").each( function() {
var href= $(this).attr("href");
if (href.length && ((pathname.indexOf(href) >= 0) || ((url.indexOf(href) >= 0) ){
$(this).addClass("active");
}
});
(not tested)
Upvotes: 1
Reputation: 3967
window.location.pathname
only gives you the path. Perhaps you meant href.indexOf(pathname)
?
Upvotes: 0