4

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.

1 Answer 1

7

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

:-)

Sign up to request clarification or add additional context in comments.

3 Comments

One more question if possible. This works well with webkit browsers, but in firefox the page scrolls to where the hidden div was, not to where it now resides (at the top of the specified section). Is there something else I'm missing? Thanks again in advance. $(document).ready(function() { var tabContainers = $('div.tabs > div'); var hash = window.location.hash; if(hash != "") { tabContainers.hide().filter(hash).show(); $('div.tabs ul.tabNavigation a').removeClass("selected"); $('[href="' + hash + '"]').addClass("selected"); } });
Not sure if related, but your '.filter(hash)' look weird. Hash variable contains hash string, it makes no sense for filter function. You probably meant '.filter($('a[href="' + hash '"]')'. Also check code for errors in console.
Yeah, I'm not getting any errors in console. That specific line of code is for displaying the correct hidden div. It seems to work fine, but I understand the weird syntax, but I don't think it's part of the "hash jump" problem... Thanks though, I appreciate it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.