DEV Community

Adam La Rosa
Adam La Rosa

Posted on

Infinite Scroll

Concerning infinite scroll in JavaScript I happened to come across this solution.

var listElm = document.querySelector('#infinite-list');

// Add 20 items.
var nextItem = 1;
var loadMore = function() {
  for (var i = 0; i < 20; i++) {
    var item = document.createElement('li');
    item.innerText = 'Item ' + nextItem++;
    listElm.appendChild(item);
  }
}

// Detect when scrolled to bottom.
listElm.addEventListener('scroll', function() {
  if (listElm.scrollTop + listElm.clientHeight >= listElm.scrollHeight) {
    loadMore();
  }
});

// Initially load some items.
loadMore();

Here we have three javascript methods that are ran against our main element: scrollTop, clientHeight, and scrollHeight.

scrollTop, when applied to an HTML element, is a measurement of the distance from the top of the element to its top most visible content.

clientHeight, on the other hand, is the inner height of the element in pixels.

scrollHeight then is the height of an element's content, including that which is not visible on the screen.

In our solution we identify the element in question, labeled by the "infinite-list" id. Next we define our function which will add new items to the unordered list, declaring which item we are at then defining a function which will add more items to the list.

Finally, we add an event listener to our initial element, listElm. This takes the size of our initial element and checks to see if after scrolling the inner height is greater than or equal to the total height of the element.

If it is, run our function again to add more elements! Forever!! :)

Top comments (0)