infinite-scroll icon indicating copy to clipboard operation
infinite-scroll copied to clipboard

Browser back button not working correctly when used with history push

Open robsimpsondesign opened this issue 6 years ago • 1 comments

I've come across an issue when using the browser back button and the history: "push" setting.

I've forked the codepen demo that replicates the issue: https://codepen.io/robsimpson/pen/aRJrwr https://codepen.io/robsimpson/full/aRJrwr

I only changed the code in:

$('.container').infiniteScroll({
  path: getPenPath,
  append: '.post',
  status: '.page-load-status',
  history: 'push',
  historyTitle: true,
  debug: true,
});

Steps to replicate the issue (replicated in Google Chrome):

  • Scroll to page 3 (3a - Masonry gets horizontalOrder heading)
  • Click the browser back button (this updates the URL but doesn't go back to the previous section on the page or fire off any events in the console with debug: true set)
  • Click the browser back button again (this keeps the URL the same, goes to the previous section and fires off event in the console)

I've not come across anyone else raise an issue like this so wondering if I've just not set something up correctly or what.

robsimpsondesign avatar Oct 10 '18 11:10 robsimpsondesign

Thanks for reporting this issue. Currently, Infinite Scroll does not provide an easy feature to support jumping back to pages with history: 'push'. Add a 👍 reaction to this issue if you would like to see this feature added. Do not add +1 comments — They will be deleted.


You can implement this feature by adding this JavasScript:

if ( 'scrollRestoration' in history ) {
  history.scrollRestoration = 'manual';
}

window.addEventListener( 'popstate', function( event ) {
  var popIndex = getPoppedPageIndex();
  if ( popIndex === undefined ) {
    return;
  }
  var scrollPage = infScroll.scrollPages[ popIndex ];
  window.scrollTo( window.pageXOffset, scrollPage.top );
});


function getPoppedPageIndex() {
  var pages = infScroll.scrollPages;
  for ( var i=0; i < pages.length; i++ ) {
    var page = pages[i];
    if ( page.path == location.href ) {
      return i;
    }
  }
}

This does rely on scrollRestoration which is unsupported in IE & Edge.

desandro avatar Oct 12 '18 15:10 desandro