0

Here is my code:

http://jsfiddle.net/h3ctt/

If you navigate to www.example.com/page.html#example-name1 without having loaded the page first it will show the whole page and not the requested content.

However if you navigate to the link once the page has loaded it will work and show the desired content.

This is very odd. Does anybody have a fix for this?

2
  • you need to run your code on page load as well as on hash change, however also take into account that some browsers trigger onhashchange on page load if there is a hash iirc. Commented Feb 25, 2013 at 20:24
  • Could you give me an example of this as i am very new to JS/ jQuery Commented Feb 25, 2013 at 20:27

2 Answers 2

1

You should check the hash onload and onhashchange

// On page load
$(document).ready(function(){
    // When the hash (#something) changes
    window.onhashchange = function() {
        doAction();
    };

    doAction();

    function doAction() {
        // get the current hash minus '#'
        var profileId = window.location.hash.substr(1);

        if(profileId != '') {
            // hide all profiles
            $('.profile').hide();
            // show only the appropriate profile
            $('#' + profileId).show();
        }
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

It works. My only gripe with it is that I want to display all of the content at once where there is no "'#' + profileId". Could this be done through the use of an IF statement, if so how would this be implemented?
what do you mean by "display all of the content at once"? do want to display profile 1 and profile 2 once there is no "'#' + profileId"? or you want to display the first element if no hash?
The former, display profile 1 and profile 2 if there is no "'#' + profileId".
0

I'm relatively sure you can't display that functionality on a jsfiddle, however, if you were on a proper page, page.html#example-name1 in the url bar should result in the functionality you want to display. In order to make it work on a proper page however, you would have to do what aboodred1 suggested with your code., i.e, running the code on hashchange. This is in order to ensure that when the url is changed, it displays that particular content.

4 Comments

But then when you load the page without any #example, how can you make it to show all the content.
@Simon, so do you want to show all content on page load? Or are you saying you want to choose a non-specific element?
I want all the content on the page to load. However when the URL is changed to page.html#example1, the page only displays the selected div.
maybe an IF statement is needed

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.