Jack Cash
Jack Cash

Reputation: 149

Add class to current page link with jQuery only works for relative but not absolute links

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

Answers (2)

Jason Y
Jason Y

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

itamar
itamar

Reputation: 3967

window.location.pathname only gives you the path. Perhaps you meant href.indexOf(pathname) ?

Upvotes: 0

Related Questions