JSFiddle - React, Tailwind, and code Playground
HTML
<div class="my-list">
</div>
CSS
.my-list {
min-height: 10rem;
width: 80%;
padding: 1rem;
left: 0;
right: 0;
margin: 0 auto;
text-align: center;
background: #ccc;
}
.list-item {
display: inline-block;
width: 9rem;
height: 9rem;
margin: 1rem;
background: #fff;
line-height: 9rem;
color: #999;
font-size: 2rem;
}
JavaScript
var InfScroll = function(selector) {
this.triggerDistance = 300;
this.addItemsCount = 20;
this.itemsCreated = 0;
this.listElm = document.querySelector(selector);
document.addEventListener("scroll", this.onScroll.bind(this));
};
// on scroll, check if near to botttom and add more items
InfScroll.prototype.onScroll = function(event) {
var self = this;
var scrollElm = event.target.scrollingElement;
var distanceBottom = scrollElm.scrollHeight - (scrollElm.parentElement ? scrollElm.parentElement.clientHeight : scrollElm.clientHeight) - scrollElm.scrollTop;
if (scrollElm.scrollTop <= self.triggerDistance) {
this.addElements(self.addItemsCount, true);
// remove old elements from bottom of scroll elm
for (var i = 0; i < self.addItemsCount; i++) {
self.listElm.childNodes[self.listElm.childNodes.length - 1].remove();
}
// scroll view back
scrollElm.scrollTop = self.triggerDistance*2;
}
if (distanceBottom <= self.triggerDistance) {
this.addElements(self.addItemsCount, false);
// remove old elements from top of scroll elm
for (var i = 0; i< Math.floor(self.addItemsCount); i++) {
self.listElm.childNodes[i].remove();
}
// scroll view back
scrollElm.scrollTop -= self.triggerDistance;
}
};
// add new items to the infinate scroll list
InfScroll.prototype.addElements = function(total, top) {
var self = this;
while (total > 0) {
var newListItem = document.createElement('div');
newListItem.className = "list-item";
newListItem.innerText = self.itemsCreated++;
if (!!top) {
// add elements to top
self.listElm.insertBefore(newListItem, self.listElm.childNodes[0]);
} else {
// add elements to bottom
self.listElm.appendChild(newListItem);
}
total--;
}
};
// create new scroller, and add first 20 items
var listScroller = new InfScroll('.my-list');
listScroller.addElements(20);
listScroller.addElements(20, true);
// scroll down...