Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 937
Toni Michel Caubet Avatar asked May 22 '13 12:05

Toni Michel Caubet


People also ask

How do you check if the user can go back in browser history or not?

To check if the user can go back in browser history or not with JavaScript, we can call history. back or history.go . history.go(-1); to go back to the previous page.

How do I check my browser history stack?

history object allows you to access the history stack of the browser. To navigate to a URL in the history, you use the back() , forward() , and go() methods. The history. length returns the number of URLs in the history stack.


2 Answers

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

like image 91
yoelp Avatar answered Oct 09 '22 17:10

yoelp


You wouldn't need to specifically see whether the next or back button is triggered. 'statechange' is the event that will be triggered when next or back button is pressed. So based on the url change you can manipulate your html content.

Also, statechange is triggered on different occasions as well in different browsers. Chrome for example loads the statechange event as soon as any page loads, even on refresh whereas this is not the case for firefox.

like image 1
Karthik Avatar answered Oct 09 '22 17:10

Karthik