Search code examples
jqueryajaxloadback

Using the Back Button with Jquery Ajax .Load


I am using jQuerys .load to Ajax in new content, but this means my back button in my browser is disabled. Is there a way to get the back button to work and show the content that was previously loaded?

This is the code I am using to load the div with new ajax content:

$(".itm1 a").click(function(evt) {
     var page = $(this).attr('href');
     $("#page1").load(page, function() {
        $(this).hide().fadeIn("slow"); 
     });
     evt.preventDefault();
  });

If you need anymore explanation of how I am doing this let me know! PLEASE HELP!!!


Solution

  • You could try the following:

    function load(page) {
        window.location.hash = page;
    }
    

    This can be used to add the hash to the page you are loading.

    And on loading you check if hash exists and load the page:

    window.onload = function() {
        if (window.location.hash.length > 1) {
            page = window.location.hash.split("#")[1];
            load(page);
        }
    
    }
    

    Edit:

    I was a bit quick when reading your question.. For the best performance and compatibily I would recommend you to try the following plugin: https://github.com/cowboy/jquery-hashchange