whist
whist

Reputation: 65

Using a jquery variable as an href selector

Apologies for this basic question, but I am noob stumped.

The below code works fine. What I wish to do is take the hash stored as a variable and target an href on the page with the same hash/target id, (eg. page that link is on = page.php#options , link= <a href="#options"> ), adding a class to the specific link.

eg. instead of #options I'd like it to be whatever (if anything) is stored in the variable hash. I've tried many combinations of $('[href="hash"]') , $('a[href=hash]') etc, but my jquery isn't that fluent so I'm not sure where I am making mistakes.

The only thing I can think is that the hash stored may not include the "#" which the targeted href calls for, but that might be a stretch.

$(document).ready(function() {

    var hash = window.location.hash;

    if(hash != "") {
        $('[href="#options"]').addClass("selected");
    }       
});

I hope this makes sense, any insight would be appreciated. Thanks in advance.

Upvotes: 4

Views: 5734

Answers (1)

spacevillain
spacevillain

Reputation: 1336

$('[href="' + hash + '"]').addClass("selected");

:-)

Upvotes: 7

Related Questions