Steven
Steven

Reputation: 18859

Perform action based on hash tag in URL

On my page, I have:

<a href="#1">Link 1</a>
<div></div>
<a href="#2">Link 2</a>
<div></div>
<a href="#3">Link 3</a>
<div></div>

Say a user goes to this page:

http://www.mysite.com/vendors#3

Then I'd like to add a css class to the link with href="#3". How can I do that with jQuery?

Upvotes: 0

Views: 794

Answers (2)

Shaz
Shaz

Reputation: 15867

window.onhashchange = (function() {
    var newHash = window.location.hash;
    $('a[href="' + newHash + '"]').addClass("yourClass");
    return arguments.callee;
})();

This will run when the document has been accessed and when you click on a link referencing a hash.

Upvotes: 1

mrtsherman
mrtsherman

Reputation: 39872

Something like this should do it. You check the window hash value.

$(document).ready( function() {
    $('a[href="' +window.location.hash + '"]').addClass('activeLink');
});

You might need to add the # in there manually. Forget if it is included in hash value.

Upvotes: 3

Related Questions