Here's an infinite/endless scrolling code snippet written in native JavaScript:
window.onscroll = function () {
if (window.scrollY > (document.body.offsetHeight - window.outerHeight)) {
console.log("It's working!");
}
}
To add a delay to this function execution(if you are sending requests to a server this is a must) you can write it like this:
window.onscroll = infiniteScroll;
// This variable is used to remember if the function was executed.
var isExecuted = false;
function infiniteScroll() {
// Inside the "if" statement the "isExecuted" variable is negated to allow initial code execution.
if (window.scrollY > (document.body.offsetHeight - window.outerHeight) && !isExecuted) {
// Set "isExecuted" to "true" to prevent further execution
isExecuted = true;
// Your code goes here
console.log("Working...");
// After 1 second the "isExecuted" will be set to "false" to allow the code inside the "if" statement to be executed again
setTimeout(() => {
isExecuted = false;
}, 1000);
}
}
I use it in my ASP.NET MVC 5
project and it works like a charm.
Note:
This code snippet doesn't work on some browsers(I'm looking at you IE). The window.scrollY
property is undefined
on IE.