I have a page with some fields. As soon as the user changes the value of the selection 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 the key and value, for example.
parameterNames.push({key:"name", value:"foobar"});
The following code restores the state when the user clicks the Back or Forward button in a browser. It works, but behaves unpredictably.
For example, I change three selection fields (by creating three history entries). Then I come back. restoreState is executed, one selection field is changed accordingly. But the browser itself remains in the same position in history (cannot get ahead, anyway the same number of entries in the history).
Then I press the back button again. This time the state object will be the same as the one that delivered the list time that I clicked. However, the browser moves one entry in the story.
The third time I click the "Back" button, the next selection field changes, but the browser remains in the state until I click the 4th time.
Can someone 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'); } }); };