Search code examples
jqueryhtmlapibrowser-historyhistory.js

History API html5, how to know when user clicked in next/back browser buttons?


I am getting familiar with the html5 History API, but I am using history.js to extend the compatibility,

I have one question and it's that, how can I know in:

            History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
                var State = History.getState(); // Note: We are using History.getState() instead of event.state
                        /* Condition here to know if this change is a back or next button, and wich one?? */
            }); 

This is my "whole" code...

var the = this;
            var History = window.History;
            if ( !History.enabled ) {
                return false;
            }
            /* Store the initial content*/
            History.replaceState({
              content: $('#main').html()
            }, document.title, document.location.href);
            /* Bind to StateChange Event */
            History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
                var State = History.getState(); // Note: We are using History.getState() instead of event.state
                //console.log(State);
                //History.log(State.data, State.title, State.url);
                console.log(history.length);
            });         
            /* triggers */
            $(document).on('click','a',function(e){
                e.preventDefault();
                var href = $(this).attr('href');
                var title = $(this).text();
                if(href == '#')
                    href = title;
                $.get('portfolio.html',function(data, response){
                    var html = $(data).find('#main-content').html();
                    //console.log(html);


                    $('#ajax-load').html(html);
                    History.pushState({ content: html}, title, href);
                    $('#ajax-load').css({ position:'absolute', 
                                          right: -$(window).width(), 
                                          top: the.header.height(), 
                                          width: $(window).width(),
                                          zIndex:999
                    }).animate({ right: 0 },300,function(){
                        console.log($('#main-content').length);
                        console.log($('#ajax-load').length);
                        $('#main-content').html(html);
                        $('#ajax-load').html('');
                    });

                });

            });

Because the only reason I should actually check for the history is for the NEXT/BACK button, right? otherwise the anchor href rules

-EDIT-

basically i need the condition from here

History.Adapter.bind(window,'statechange',function(){ 
                var State = History.getState(); 
                var condition = false;
                if(condition){
                    console.log('You clicked the next/back button');
                }
}); 

Thanks in advance


Solution

  • You can keep track of all states (links) in an Array and on popstate (or statechange) compare the new location to the old one in the array so you will know which way the user went in history (back or fwd).

    Or you can pass along in the state obj (the first param to pushState) a time stamp and compare that to the old

    Option 1(has issues - don't use)

    (function(){
        /*adding some init vars*/
        var the = this, arr = [], currPage;
        var History = window.History;
        if ( !History.enabled ) {
            return false;
        }
        /* Store the initial content*/
        History.replaceState({
          content: $('#main').html()
        }, document.title, document.location.href);
        /* add to arr*/
        arr[arr.length] = document.location.href;
        /*keep track of where we arein arr*/
        currPage = arr.length -1;
        /* Bind to StateChange Event */
        History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
                var position, button;
                var State = History.getState(); // Note: We are using History.getState() instead of event.state
                //console.log(State);
                //History.log(State.data, State.title, State.url);
                console.log(history.length);
                position = arr.indexOf(document.location.href);
                button = position > currPage ? "fwd" : "back";
                currPage = position;
                console.log("You pressed The "+ button + " Button");
            });         
            /* triggers */
            $(document).on('click','a',function(e){
                e.preventDefault();
                var href = $(this).attr('href');
                var title = $(this).text();
                if(href == '#')
                    href = title;
                $.get('portfolio.html',function(data, response){
                    var html = $(data).find('#main-content').html();
                    //console.log(html);
    
    
                    $('#ajax-load').html(html);
                    History.pushState({ content: html}, title, href);
                    /* add to arr */
                    arr[arr.length] = href;
                    /* keep track */
                    currPage = arr.length -1;
                    $('#ajax-load').css({ position:'absolute', 
                                          right: -$(window).width(), 
                                          top: the.header.height(), 
                                          width: $(window).width(),
                                          zIndex:999
                    }).animate({ right: 0 },300,function(){
                        console.log($('#main-content').length);
                        console.log($('#ajax-load').length);
                        $('#main-content').html(html);
                        $('#ajax-load').html('');
                    });
    
                });
    
            });
    
    }())
    

    This option has a problem that it will get confused if the same link will be in the history more than once

    Option 2

        (function(){
        /*adding some init vars*/
        var the = this, currPageTime;
        var History = window.History;
        if ( !History.enabled ) {
            return false;
        }
        /* Store the initial content*/
        /* remember the current time */
        currPageTime = new Date().getTime();
        History.replaceState({
          content: $('#main').html(),
          time : currPageTime
        }, document.title, document.location.href);
        /* Bind to StateChange Event */
        History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
                var pageTime, button;
                var State = History.getState(); // Note: We are using History.getState() instead of event.state
                //console.log(State);
                //History.log(State.data, State.title, State.url);
                console.log(history.length);
                /*NOTE: I never used getState so i dont know if State.time will exist, if not change it to whatever  holds the time we passed earlier */
                pageTime = State.time;
                button = pageTime > currPageTime ? "fwd" : "back";
                currPageTime =  pageTime;
                console.log("You pressed The "+ button + " Button");
            });         
            /* triggers */
            $(document).on('click','a',function(e){
                e.preventDefault();
                var href = $(this).attr('href');
                var title = $(this).text();
                if(href == '#')
                    href = title;
                $.get('portfolio.html',function(data, response){
                    var html = $(data).find('#main-content').html();
                    //console.log(html);
    
    
                    $('#ajax-load').html(html);
                    /* keep track of time */
                    currPageTime = new Date().getTime();
                    History.pushState({ content: html, time: currPageTime}, title, href);
                    $('#ajax-load').css({ position:'absolute', 
                                          right: -$(window).width(), 
                                          top: the.header.height(), 
                                          width: $(window).width(),
                                          zIndex:999
                    }).animate({ right: 0 },300,function(){
                        console.log($('#main-content').length);
                        console.log($('#ajax-load').length);
                        $('#main-content').html(html);
                        $('#ajax-load').html('');
                    });
    
                });
    
            });
    
    }())
    

    PS: I haven't tested if it works, if it doesn't work please make a fiddle and I'l try to fix it