Skip to content

Instantly share code, notes, and snippets.

@pbnkp
Created January 14, 2024 10:48
Show Gist options
  • Save pbnkp/adf8770226cfe5a53ef03575f6d05344 to your computer and use it in GitHub Desktop.
Save pbnkp/adf8770226cfe5a53ef03575f6d05344 to your computer and use it in GitHub Desktop.
Infinite Scroll (pure JS)
<ul id='infinite-list'>
</ul>
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();
#infinite-list {
/* We need to limit the height and show a scrollbar */
width: 200px;
height: 300px;
overflow: auto;
/* Optional, only to check that it works with margin/padding */
margin: 30px;
padding: 20px;
border: 10px solid black;
}
/* Optional eye candy below: */
li {
padding: 10px;
list-style-type: none;
}
li:hover {
background: #ccc;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment