Infinite Scrolling Through Paginated Results With jQuery

This is a Rosetta Code post.

Story

You have a page on your website that displays data from the jsonplaceholder todos rest API. All 200 rows are displayed at once which is inefficient.

Task

Pagenate through n results using infinite scrolling like a Facebook feed.

You must

  • Use jQuery and javascript
  • Paginate using _start (the page) and _limit (the size) for each request.
  • When the user scrolls to the bottom of the screen fetch the next n results auto-magically \ :D /

The user will have the experience of infinite scrolling which will save their data and reduce unnecessary requests.

Solutions

Once the document loads fire the first get, there after listen to the scroll event, use checkpos to determine if the user is at the bottom of the screen, increment the start variable and get the next page.

Repeat this until the known max is reached.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
let start = 0;
let limit = 40;
let max = 200;

function checkpos() {
let top = Math.floor($(window).scrollTop())
let docheight = $(document).height()
let windowheight = $(window).height()
let percentage = (100 * (top + windowheight)) / docheight;
return percentage == 100;
}

function handlerow(todo) {
$("#table tbody:last").append("<tr><td>" + todo.id + "</td><td>" + todo.title + "</td></tr>");
}

function get() {
$.get("https://jsonplaceholder.typicode.com/todos/?_start=" + start + "&_limit=" + limit, function (data) {
data.map(todo =>
handlerow(todo)
);
});
}

$(document).ready(function () {
get()
$(window).scroll(function () {
if (checkpos()) {
start = start + limit;

if (start >= max) {
return;
}
get();
}
});
});

Limitations include

  • This will only fire when the user scrolls right to the bottom, a percentage of 95 could be used instead however the scroll event will need tweaking. checkpos is already doing a percentage calculation with this in mind
  • If the initial get returns less data than that which causes the y-axis scroll to display, the scroll listener will never fire
  • The API’s used in checkpos may not work in all browsers ¯\(ツ)

References