Skip to content

Instantly share code, notes, and snippets.

@ahwm
Created November 17, 2020 22:44
Show Gist options
  • Save ahwm/fe650c8fe0f8e8c1ddfdaaaddfd29373 to your computer and use it in GitHub Desktop.
Save ahwm/fe650c8fe0f8e8c1ddfdaaaddfd29373 to your computer and use it in GitHub Desktop.
Infinite Scroll ability with plain JavaScript (no jQuery)
/*
* Infinite Scroll js, no jQuery reliance
*
*/
var activeCall = false, triggerElem, div = document.querySelector('#dataParentDiv > .row'), skip = 21, last = false;
document.addEventListener('DOMContentLoaded', function () {
if (document.querySelectorAll('.product-item').length <= 21)
last = true; // don't attempt to inifinite scroll for less than initial results
else
getTriggerElement();
window.addEventListener('scroll', function () {
if (last || activeCall)
return;
var bounds = triggerElem.getBoundingClientRect();
if (bounds.top < (window.innerHeight + 300) && !activeCall && !last) {
activeCall = true; // prevents multiple calls all at once
minAjax({
url: '/api/url',
type: 'GET',
data: {
categories: [1,2,3,4],
skip: skip
},
success: function (data) {
var elems = JSON.parse(data);
skip = skip + elems.length;
last = elems.length < 15;
for (var i = 0; i < elems.length; i++) {
div.insertAdjacentHTML('beforeend', elems[i]); // assuming API endpoint simply returns pre-built HTML
// other work can be done here for anything else
}
getTriggerElement();
activeCall = false;
}
});
}
});
});
function getTriggerElement() {
var elements = document.querySelectorAll('.product-item');
triggerElem = elements[elements.length - 3];
}
// minAjax: https://github.com/flouthoc/minAjax.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment