JSFiddle - React, Tailwind, and code Playground
by ashish shubham
HTML
<div id="container">
<div id="items">
</div>
<div id="scrollHolder"></div>
</div>
CSS
#container {
height: 300px;
width: 80%;
border: 1px solid black;
overflow-y: auto;
}
.item {
display: inline-block;
width: 50px;
height: 50px;
background-color: #d1d3d8;
margin: 10px;
}
#scrollHolder {
height: 5px;
width: 100%;
background: red;
}
JavaScript
function getContent(offset, num) {
// Do not change this method.
const content = [];
for (i = 0; i < num; i++) {
content.push(offset + i);
};
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(content);
}, Math.random() * 5000);
})
}
var createItem = function(item) {
let itemDiv = document.createElement('div');
itemDiv.className = 'item';
itemDiv.innerHTML = item;
return itemDiv;
}
const containerDiv = document.getElementById('container');
const scrollHolder = document.getElementById('scrollHolder');
const itemHolder = document.getElementById('items');
var currOffset = 0;
const itemsToRender = 40;
// Inital rendering of n elements
function renderNextElements() {
getContent(currOffset, itemsToRender).then(function(res) {
res.forEach(function(item) {
let itemDiv = createItem(item);
itemHolder.appendChild(itemDiv);
console.log(currOffset, itemsToRender);
});
currOffset += itemsToRender;
});
}
renderNextElements();
containerDiv.onscroll = function(e) {
// Check if scrollHolder in view
let scrollHolderPos = scrollHolder.getBoundingClientRect();
//console.log(scrollHolderPos.top, scrollHolderPos.bottom, containerDiv.scrollTop, containerDiv.clientHeight, containerDiv.getBoundingClientRect().top);
if (scrollHolderPos.top < (containerDiv.clientHeight + containerDiv.getBoundingClientRect().top)) {
console.log('in view')
renderNextElements();
}
}