18

I've got a page with some select-fields. Once the user changes the value of a select-field, a new history-object is created using the values of all select-fields as a state object:

$(".chosen-select-field").chosen().change(function() {
    $(".chosen-select-field").each( function ( index ) {
        parameterNames[index].value = $( this ).val();
    });
    history.pushState(parameterNames, '', newUrl);
});

parameterNames is an array of objects containing a key and value e.g.

parameterNames.push({key:"name", value:"foobar"});

The following code restores the state when the user clicks on the back or forward-button in the browser. It works but behaves unexpected.

For example I change three select-fields (creating three history entries). Then I go back. restoreState is executed, one select-field is changed accordingly. But the browser itself remains at the same position in the history (can't got forward, still the same number of back-history entries).

Then I click again on the back-button. This time the state-object is the same as the one delivered the list time I clicked. The browser moves back one entry in the history though.

The third time I click on the back button the next select-field is changed but the browser stays again at the state unless I click a 4th time.

Can anyone explain what I'm doing wrong?

var restoreState = function(event) {
    event = event.originalEvent;
    parameterNames = event.state;
    $(".chosen-select-field").each( function ( index ) {
        if ($( this ).val() != parameterNames[index].value){
            $( this ).val(parameterNames[index].value).change();
            $( this ).trigger('chosen:updated');
        }
    });
};

// Bind history events
$(window).bind("popstate",restoreState);
Michael Rovinsky
  • 3,980
  • 3
  • 11
  • 23
Hedge
  • 13,498
  • 35
  • 122
  • 223
  • 2
    on popstate (e.g. back), you are calling "restoreState", which loops the fields, and potentially calls .change(), which does history.pushState again. I suggest doing replaceState if popstate event is fired. – George Mar 09 '18 at 23:20
  • https://stackoverflow.com/questions/20156939/how-to-handle-back-button-while-changing-the-browser-url-with-html5-pushstate/20157851#20157851 – Tim Vermaelen Dec 07 '18 at 15:11

0 Answers0