Implementing infinite scroll

I would like to add infinite scrolling to a page I have that lists items from a database table. I haven’t found any tutorials that use infinite scrolling on data taken from a database, and most of the others seem to use jQuery.

Can anyone point me in the direction of a decent tutorial?

Have you seen this?

It seems to take a vanilla JavaScript perspective, walks you through the logic and I think with a little more customization you can make it work for any data you pull from a database.

2 Likes

Hi @Gandalf ,

Here is an implementation with intersection observers and promises.

In place of the new Promise bit of the loadItems script I would imagine you would would want to use the fetch api to fetch data from the database.

function loadItems(number) {
  new Promise((resolve) => {
    setTimeout(() => {
      resolve(Array(number).fill('A List Item'));
    }, 1000);
  }).then(data => {
    const html = data.map(item => `<li>${item}</li>`);
    $list.innerHTML += html.join('');
  })
}
2 Likes

Many thanks, guys. I had not seen either of those. What it is to have choices. :biggrin:

1 Like

Yes, indeed. A PHP routine to query the db and bring back the data, which could be a bit of a challenge. :slight_smile:

1 Like

Infinite scrolling is no different than paging implemented in a slightly different manner. If you’ve ever done a paged approach, then it shouldn’t be that hard to adapt to.

1 Like

My pagination is all PHP. However, I am making good progress with infinite scroll. :slight_smile: The only thing (I think) that I’m stuck with is where to keep track of the offset (or page number). Is it best in a session variable, cookie or somewhere else?

I’d probably just keep it in a hidden element on the page myself.

1 Like

Ooh, I’d not thought of that!

Hi @Gandalf ,

I’ve been reading through the following interesting and very in-depth article (still reading). There is a part that covers handling the offsets using a mock database. The offsets and the chunk data are passed in object format.

const chunk = items.slice(start, limit);
const cursorInfo = { chunk, nextCursor: start + limit, prevCursor: start, size: chunk.length };
return new Promise((resolve) => resolve(cursorInfo));

As I say still reading, but I think worth a look at.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.