Search code examples
javascriptjqueryhtmlhtml5-history

How to make forward button work on this example using HTML5 history?


In this example we manage to make back button work but forward button seem to be a problem, when forward button is pressed, #modal should reappear but it did not. Any idea to fix it?

$(window).bind('popstate', function() {
  $('#modal').hide();
});

$(".view").click(function() {
  history.pushState(null, null, null);
  $("#modal").show();
});
#modal {
  position: relative;
  display: none;
  height: 100px;
  width: 100px;
  background-color: grey
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button class="view">Click</button>
<div id="modal"></div>

Here is JSBin

Thanks!


Solution

  • By pushing all null onto the history you aren't coupling the state / view of the page in any way. Are you aware that the popstate event is also fired when you move forward along the stack too?

    Most people tend to use relative URLs (or fragments) known as "routing" to resolve history / content but you can also use the first parameter of pushState to add data - how you manage this mechanism on a larger scale is out of scope but a simple example would be as follows:

    $(window).bind('popstate', function() {
        var state = history.state || {};
        state.openModal ? $('#modal').show() : $('#modal').hide();
    });
    
    $(".view").click(function(){
        $('#modal').show();
        history.pushState({ openModal: true });
    });
    

    » demo