简体   繁体   中英

How to use browser back functionality to close a layer?

I am opening a full page layer for filtering upon button click. One can close it via button, but some do use the navigation functionality of the browser which then loads the last page instead of the on that opened it.

To fix this, I saw that there are 2 approaches. One with hash and one with browser state.

The browser state does not close the layer for me on the back button, just changes the URL so I am trying the hash option.

While it works, there is the problem that I do have multiple layers to call for example a search layer.

// show/hide filter layer
var filter_layer_toggle = function() {
    // window.history.pushState('page2', 'Title', '/page2.php');
    $("#btn_save_search").toggle()
    // more happening here
}
//this needs to be called on another event
var search_layer_toggle = function() {
    // toggles search layer elements
}
$("#filter_button, #btn_fltr").on("click", function(){
    window.location.hash = "filter";
});
document.location.hash = '';
$( window ).on( 'hashchange', function( e ) {
    filter_layer_toggle();
} );

How can I support the browser back function, while using multiple layers?

You could create a function that checks the hash and then toggles the appropriate layer using a switch for example.

Then you call that function on both load and hashchange events.

You'd have something like:

function parseHash() {
  switch(window.location.hash) {
    case '#filter':
      filter_layer_toggle();
      break;
    case '#search':
      search_layer_toggle();
      break;
    default:
     // proceed with the not layered page
  }
}

And on the hashchange event you call parseHash()

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