Marcus
Marcus

Reputation: 460

Adding a class to an a element with a particular href using hash

I'm trying to add an 'active' class to a particular element based on the URL hash but it's not working as I expect.

Here's my code:

var hash = window.location.hash.substr(1);
if(hash != false) {
    $('.products #copy div, #productNav li a').removeClass('active');
    $('.products #copy div#'+hash+'').addClass('active');
    $('#productNav li a[href*="'+hash+'"').addClass('active');
}

The second jQuery statement (the one that adds the 'active' class to the div) works as expected, but the third (the one that adds the 'active' class to the link) does not.

Anybody see anything I'm doing wrong?

Thanks much
Marcus

Upvotes: 2

Views: 222

Answers (2)

Makram Saleh
Makram Saleh

Reputation: 8701

Try this instead of the third line:

$('#productNav li a[href='+hash+']').addClass('active');

Upvotes: 2

Marcus
Marcus

Reputation: 460

Never mind - I have figured this out. I was missing my end ']'.

var hash = window.location.hash.substr(1);
if(hash != false) {
    $('.products #copy div, #productNav li a').removeClass('active');
    $('.products #copy div#'+hash+'').addClass('active');
    $('#productNav li a[href*="'+hash+'"]').addClass('active');
}

Upvotes: 2

Related Questions