0

I am making a website and I use jQuery to load my html pages inside divs, so the main index html remains intact that way. The problem is that if a user is browsing an html that loads inside a div and tries to refresh his browser(F5) the content gets "lost" since it's only one page(index.html).

Is there a way to get around this?

<a onclick='$("#content").load("page1.html");'>Page1</a> 
<div id="content"></div>
3
  • 1
    you mean you want to keep showing the content if the user refreshes? Commented May 22, 2013 at 8:00
  • Do this $("#content").load("page1.html"); on page load. Commented May 22, 2013 at 8:01
  • @pXL maybe its not always page1.html but dynamic.. Commented May 22, 2013 at 8:06

1 Answer 1

3

There's two solutions for that. If a user clicks a link, you add a hashtag to the url. For example:

<a onclick='$("#content").load("page1.html"); window.location.hash = "page1.html";'>Page1</a> 

Then, in your jQuery, you check for a hashtag when a user visits the site:

$(function() {
    if (window.location.hash.length) {
        var hash = window.location.hash.replace('#', '');

        $("#content").load(hash);
    }
});

Secondly, you could use cookies but I think the hash way works fine, too :)

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

9 Comments

Looks great but still doesn't work for me. Does window.location.hash = "page1.html"; page1.html must be the same path as the html file? Although I tried that too.
The hastag is added to the url when you click the link but hitting F5 acts like before, the content doesn't remain there.
well have you inserted the jquery code in your page? or maybe you have a scripts.js where you can add it?
Yes I added the script. I am testing it through xampp by the way. The html files are not in the same folder with index though, does that have to do anything with this not working?
|

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.