Skip to content Skip to sidebar Skip to footer

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(h

Solution 1:

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');
}

Solution 2:

Try this instead of the third line:

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

Post a Comment for "Adding A Class To An A Element With A Particular Href Using Hash"