Skip to content

Instantly share code, notes, and snippets.

@ahwm
Last active December 12, 2024 17:47
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,
triggerSelector = '.product-item',
triggerElem,
pixelsBeforeTrigger = 300,
div = document.querySelector('#dataParentDiv > .row'),
skip = 21,
last = false;
document.addEventListener('DOMContentLoaded', function () {
if (document.querySelectorAll(triggerSelector).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 + pixelsBeforeTrigger) && !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(triggerSelector);
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