Nick
Nick

Reputation: 169

Jquery using load() and back button

I have secure.php page which contains the header, css, etc. In the secure page, I have a div called dynamic, where the contents from other php pages are loaded into.

The pages that have the content are page1.php and page2.php.

My simplified secure php code:

<!DOCTYPE html>
<head>    
    <script src="js/jquery-1.10.0.min.js"></script>
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <script src="js/modernizr-2.6.2-respond-1.1.0.min.js"></script>
    <script src="js/jquery.ba-hashchange.min.js"></script>
    <script>

    $(document).ready(function() {
        loadPage1();
    });
    $(function() {
  $(window).hashchange( function() {

    if (location.hash == "#page1") {
        loadPage1();
    };
    if (location.hash == "#page2") {
        loadPage2();
    };
  })

  // Since the event is only triggered when the hash changes, we need to trigger
  // the event now, to handle the hash the page may have loaded with.
  $(window).hashchange();

});


    function loadPage1() {
        $('#dynamic').load('page1.php');
    }

    function loadPage2() {
        $('#dynamic').load('page2.php');
    }

</script>

    </head>
    <body class="bodysecure">        
        <div id="headermenu">
            <div class="menuitem"><a href="#page1" onmouseover="" onClick="loadPage1()">Page1</a></div>
            <div class="menuitem"><a href="#page2" onmouseover="" onClick="loadPage2()">Page2</a></div>
        </div>

            <div id="dynamic"></div>

    </body>
</html>

My current code is working just fine. Perhaps it could be better programmed, but that's not the issue here.

The problem is, that the back/forward buttons aren't working and you can't bookmark the specific page, since the url is always secure.php. I went searching for a solution and saw many many plugins that are pretty complicated (I'm just a beginner).

Is there an easy way to do this without a plugin? Like use the hashtag? And could anyone please provide me an example, perhaps on fiddle?

Upvotes: 1

Views: 3806

Answers (1)

putvande
putvande

Reputation: 15213

You could do something like:

// Document ready checks if the hash is set in which it loads the correct page.
// on default (if no hash set) page1.php will be the page.
$(document).ready(function() {
    var page = window.location.hash || 'page1.php'; 
    loadPage(page);
});

// This loads the actual page.
function loadPage(page) {
    $('#dynamic').load(page);
    window.location.hash = page;
}

Upvotes: 1

Related Questions