0

I have a problem with jquery, for example, i have this code:

<a href="#" id="docs"><img id="icon" src="icons/docs.png"/></a>

$("#docs").click(function() {
$("#content").load("docs.php").hide().fadeIn("slow");})

All the things works fine, except that when i reload the website it goes back to the previews situation, but i want the website to still as it is when the link clicked.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Omer N Omer
  • 163
  • 1
  • 5
  • You can't, but you can warn the user that bad things will happen. http://stackoverflow.com/questions/3221161/how-to-pop-up-an-alert-box-when-the-browsers-refresh-button-is-clicked – asawyer Feb 28 '12 at 21:53
  • It's possible that you could use jQuery/ajax to set a cookie/session, then use server side code to conditionally load the same thing the ajax loads if the cookie is there. If the cookie is set as soon as the content is loaded with ajax, then the user can reload the page and the server will load the content on page load. – Code Junkie Feb 29 '12 at 00:34

2 Answers2

2

You can use the hashtag in the URL to detect this.

First, put your ajax request in a function, and then call this function in two cases: a) when the user clicks on the link; b) if the hashtag is "#load_docs".

$(document).ready(function() {
    function load_contents() {
        $("#content").load("docs.php").hide().fadeIn("slow");
    }

    $("#docs").click(function() {
        load_contents();
    });

    var hashtag = window.location.hash;
    if (hashtag == "#load_docs") load_contents();

});    

Don't forget to add href="#load_docs" to your link:

<a href="#load_docs" id="docs"><img id="icon" src="icons/docs.png"/></a>
mariogl
  • 1,195
  • 1
  • 10
  • 24
0

Just make sure you return false; inside the click handler.

So:

$("#docs").click(function() {
  $("#content").load("docs.php").hide().fadeIn("slow");
  return false;
})
TheDelChop
  • 7,938
  • 4
  • 48
  • 70
  • 1
    What does returning false from a click handler have to do with preventing the user from reloading the page? – villecoder Feb 28 '12 at 21:56
  • I think he's saying that he doesn't want the link '#docs' to refresh the page, return false will prevent that from happening, since it won't execute the actual click, just the code in the handler. – TheDelChop Feb 28 '12 at 21:58
  • No. He's saying (quoting here) "When I reload the website it goes back to the previews situation". He didn't say "When I click the link". – villecoder Feb 28 '12 at 22:00