简体   繁体   中英

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!

You can use "hash" instead of "history"

$(window).bind('popstate', function() {
  if(location.hash.indexOf('#modal') != -1)
      $('#modal').show();
  else
    $('#modal').hide();
});

$(".view").click(function(){
  location.hash ='#modal';
  $("#modal").show();
});

This is a demo

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM