Soup
Soup

Reputation: 137

How can I add an "active" class based on the URL?

when a user clicks on a link in the sidebar, it should stay underlined to remind them where they are. i'm trying to use jQuery to add the "active" class to the anchor if they're on the corresponding page. here's what i've got so far:

var pathy = $(location).attr('pathname');
pathy.val().replace(/\\/g, '');
if(pathy == $('#sidebar ul li a').text) {
    $(this).addClass('active');
} 
else {
}

needless to say, it really doesn't work. should i be doing this in php instead?

Upvotes: 0

Views: 93

Answers (2)

Goose
Goose

Reputation: 3279

Try this:

$('#sidebar ul li a').each(function() {
    if ($(this).text() == pathy) {
        $(this).addClass('active');
    }
});

I'm not the best with regex though, so make sure that you return your value first to ensure that it should/shouldn't match.

Edit - after comments below

It doesn't seem like you really need to do much manipulation of the string, so I don't think that a regex is necessary. Also, it will probably be better if you check the href attributes in the a tags rather than their text names, as you may want a href value of "about.php", but a text value of "About Me".

Here is what I would do:

var pathy = location.pathname; //should return something like "/filename.php"
pathy = pathy.slice(1); //this will trim the first "/" character

$('#sidebar ul li a').each(function () {
    if ($(this).attr('href') == pathy) {
        $(this).addClass('active');
    }
});

Here is a sample fiddle.

Upvotes: 1

Rottingham
Rottingham

Reputation: 2604

You are using $(this) in the wrong context. To actually select an item so you can affect it, you would use this instead:

$('[pathname="' + pathy + '"]').addClass('active');

Using the [name="value"] selector you can grab a selector to an item by its attribute.

Upvotes: 0

Related Questions