Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting my back and forwards buttons to work with ajax

My site is working much quicker thanks to some code I painstakingly modified, but I would love if the browsers' back/forwards buttons worked. Right now, with my code below, the browser address bar never changes. When someone clicks 'Back', it takes them out of the application.

Would there by any easy way of changing this so the browser's back/forward button worked? Or else if someone could point me in the right direction. Thanks for any help.

$(document).on("ready", function () {

    //I want to load content into the '.page-content' class, with ajax

    var ajax_loaded = (function (response) {

        $(".page-content")

        .html($(response).filter(".page-content"));

        $(".page-content .ajax").on("click", ajax_load);


    });



    //the function below is called by links that are described 
    //with the class 'ajax', or are in the div 'menu' 

    var history = [];

    var ajax_load = (function (e) {

        e.preventDefault();


        history.push(this);
        var url = $(this).attr("href");
        var method = $(this).attr("data-method");


        $.ajax({
            url: url,
            type: method,
            success: ajax_loaded
        });

    });


    //monitor for clicks from menu div, or with
    //the ajax class
    //why the trigger?

    $("#menu a").on("click", ajax_load);
    $(".ajax").on("click", ajax_load);
    $("#menu a.main").trigger("click");



});
like image 487
CHarris Avatar asked May 17 '13 23:05

CHarris


1 Answers

Here is a way of detecting what you are asking.

Bear in my playing with the back and forward buttons is a risky task.

window.onload = function () {

    if (typeof history.pushState === "function") {

        history.pushState("someState", null, null);

        window.onpopstate = function () {

            history.pushState("newState", null, null);

            // Handle the back (or forward) buttons here
            // Will not handle refresh, use onbeforeunload for this.
        };
    }
}
like image 97
GriffLab Avatar answered Nov 03 '22 09:11

GriffLab