RThomasDesign
RThomasDesign

Reputation: 1

Infinite Ajax Scroll - Back button takes user to incorrect page/scroll position

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?

Upvotes: 0

Views: 355

Answers (1)

user19026118
user19026118

Reputation:

Instead of the expected scroll position when using Infinite Ajax Scroll, you can modify your code to also track and restore the scroll position.

let ias = new InfiniteAjaxScroll('.collection-grid', {
  item: '.grid-product',
  next: '.pagination__next',
  //pagination: '.pagination'
});

// Store the scroll position when navigating away from the page
let scrollPosition = 0;

// Update title and URL when scrolling through pages
ias.on('page', (e) => {
  // Store the current scroll position
  scrollPosition = window.scrollY;

  document.title = e.title;

  let state = history.state;

  history.replaceState(state, e.title, e.url);
});

// Restore the scroll position when using the back button
window.addEventListener('popstate', (e) => {
  if (e.state) {
    // Set the scroll position to the stored value
    window.scrollTo(0, scrollPosition);
  }
});

In this code, I have added a scrollPosition variable to store the scroll position when the user navigates away from the page. When a new page is loaded via Infinite 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.scrollTo to 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.

Upvotes: 0

Related Questions