A client of mine wants to implement infinite scroll on their collection pages for an ecommerce (Shopify) site. I thought I'd test out Infinite Ajax Scroll (before purchasing it for other clients). I'm using the most basic implementation at the moment -- which is working to a point. Additional pages are loading in as expected, however, when a user navigates to another page, and then hits the back button, the user is taken to the bottom of the page, rather than the expected scroll position. I'm not sure what's going on here.
You can view an example page here: https://vno3ds5zbzbhfjwq-6162841667.shopifypreview.com//collections/vintage-halloween-figural-decor
Help would be appreciated and thanks!
This is the code I'm using:
let ias = new InfiniteAjaxScroll('.collection-grid', {
item: '.grid-product',
next: '.pagination__next',
//pagination: '.pagination'
});
// update title and url then scrolling through pages
ias.on('page', (e) => {
document.title = e.title;
let state = history.state;
history.replaceState(state, e.title, e.url);
});
It's my understanding that the back button should work out the gate. Do I need to track the scroll position?
Instead of the expected scroll position when using
Infinite Ajax Scroll, you can modify your code to also track and restore the scroll position.In this code, I have added a
scrollPositionvariable to store the scroll position when the user navigates away from the page. When a new page is loaded viaInfinite Ajax Scroll, the script store the current scroll position in this variable.Then, when the user uses the back button (popstate event), we check if there is a stored scroll position in the history state. If there is, you should use
window.scrollToto scroll to that position, restoring the previous scroll state.This should ensure that when a user hits the back button, they are taken to the expected scroll position instead of the bottom of the page.