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

2

7

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

Hirschfeld answered 22/5, 2013 at 12:53 Comment(2)
Have you checked out this question #6359827Monk
or this: #16548641 ??Stickney
D
2

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

Duggan answered 29/5, 2013 at 14:15 Comment(0)
E
1

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.

Equipotential answered 27/5, 2013 at 8:30 Comment(1)
I do want to know because i want to treat the response differntly in those cases... ;)Hirschfeld

© 2022 - 2024 — McMap. All rights reserved.