简体   繁体   中英

Get pagination to follow “Back” / “Forward” buttons with window.history.pushstate

I am trying to make a page of results with pagination work seamless with the back and forward buttons. If you click the "Next" button and go to page 2. I need the back button to navigate back to the first page of the results and so on. Same would go for the "jump to page" buttons. If the "active" page is page 3, and the back button is clicked I would need the "active" button to follow.

I was able to get this working with a page number appended to the url:

window.history.pushState({path:updateurl},'',updateurl,);

But can't seem to get it working with the pagination or currentPage. I was also trying to work in a:

window.history.replaceState()

On every pagination click to see if I could rewrite the history to just got back to the last state. But no luck.

I understand this is a bit complicated.

Here is the jsfiddle of my project.

Thanks for the help.

I didn't find a popstate eventlistener in your fiddle. When user click the back or forward button in the browser, this event will fire, and you can use document.location or event.state to set your page.

window.onpopstate = function(event) {
  // assuming you only have 1 query
  const index = document.location.search.split("=")[1];
  // set your currentPage
  setCurrentPage(index);
};

See the MDN reference here: https://developer.mozilla.org/en-US/docs/Web/Events/popstate

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