I wish to implement infinite scrolling with javascript and without jquery.
I am new to javascript.
After searching all over the net, I have this code.
I use requestAnimationFrame
instead of listening for scroll. I also added a throttle based on time so it doesn't overwork our page and batched the element additions:
var numElementsToAdd = 10,
offsetForNewContent = 20;
function checkInfiniteScroll(parentSelector, childSelector) {
var lastDiv = document.querySelector(parentSelector + childSelector),
lastDivOffset = lastDiv.offsetTop + lastDiv.clientHeight,
pageOffset = window.pageYOffset + window.innerHeight;
if(pageOffset > lastDivOffset - offsetForNewContent ) {
for(var i = 0; i < numElementsToAdd; i++) {
var newDiv = document.createElement("div");
newDiv.innerHTML = "my awesome new div";
document.querySelector(parentSelector).appendChild(newDiv);
}
checkInfiniteScroll(parentSelector, childSelector);
}
};
var lastScrollTime = Date.now(),
checkInterval = 50;
function update() {
requestAnimationFrame(update);
var currScrollTime = Date.now();
if(lastScrollTime + checkInterval < currScrollTime) {
checkInfiniteScroll("#scroll-content", "> div:last-child");
lastScrollTime = currScrollTime;
}
};
update();
#scroll-content > div {
background: #c0c0c0;
height: 40px;
margin-bottom: 5px;
}
test div