Scroll Position Detects The List Bottom

scrollTop plus clientHeight against scrollHeight reports the pixels remaining to the bottom, the signal infinite scroll uses before fetching more rows.

JavascriptData Fetching

Code

javascriptsnippet
34 lines
// Infinite-scroll readiness: how close is the viewport to the last row?
const feed = document.createElement('div');
feed.style.height = '300px';
feed.style.overflowY = 'scroll';
for (let i = 1; i <= 50; i++) {
  feed.append(Object.assign(document.createElement('p'), { textContent: `row ${i}` }));
}
document.body.append(feed);

// scrollTop is the scroll position inside the list; scrollHeight is the
// full content height, clientHeight the visible viewport height.
function distanceToBottom() {
  const scrolled = feed.scrollTop + feed.clientHeight;
  return feed.scrollHeight - scrolled;
}

// Near the bottom, flag the list so a spinner or fetch can start.
feed.addEventListener('scroll', () => {
  if (distanceToBottom() < 200) feed.dataset.loading = 'true';
});

// Assigning beyond the max clamps: scrollTop lands at the exact bottom edge.
feed.scrollTop = feed.scrollHeight;
console.log('scrollTop after clamp:', feed.scrollTop);
console.log('px from bottom:', distanceToBottom());
// Scroll events dispatch asynchronously: inside this same synchronous block
// the handler above has not run yet, so the flag is still unset.
console.log('loading flagged (same tick):', feed.dataset.loading === 'true');

// The scroll event fires as part of the next rendering update, before this
// frame callback runs — assert the flag there, not inline.
requestAnimationFrame(() => {
  console.log('loading flagged (after scroll event):', feed.dataset.loading === 'true');
});

Inside the snippet

The snippet is organized around the function distanceToBottom.

The one repetition in this snippet is the loop for (let i = 1; i <= 50; i++).

Points of care

  • Everything it calls is documented as part of the language core.
  • document, requestAnimationFrame exist only in browsers — a Node runtime has no shims for them out of the box.

Putting it to use

Signature: function distanceToBottom()

Look for the scrollTop after clamp:, px from bottom:, loading flagged (same tick): prefixes when the file runs; they tie each line to its step.

Core lines

feed.addEventListener('scroll', () => {
if (distanceToBottom() < 200) feed.dataset.loading = 'true';
});
return feed.scrollHeight - scrolled;
requestAnimationFrame(() => {
console.log('loading flagged (after scroll event):', feed.dataset.loading === 'true');
});

Interactive Tools for This Topic

FAQ

Does Scroll Position Detects The List Bottom run in plain Node.js?
No — it touches `document` and `requestAnimationFrame`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.