1

How do I implement infinite/endless scrolling(like Facebook) in my project without any libraries or frameworks?

Almost all guides show how to do this with jQuery, React and Angular but I want a native JavaScript implementation for infinite scrolling.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
bezbos.
  • 1,551
  • 2
  • 18
  • 33

1 Answers1

3

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.

bezbos.
  • 1,551
  • 2
  • 18
  • 33
  • @SaifTaher sorry to hear that. Are you sure you implemented it correctly? You need enough height to be able to scroll in order to trigger the `onscroll` event. – bezbos. Sep 17 '18 at 11:15
  • You said that it works with ASP.NET though... Maybe that's the problem??!! (I don't really think so) – Saif Taher Sep 17 '18 at 18:50
  • @SaifTaher what browser are you using? I'm using Google Chrome. `window.onscroll` event may not work properly on IE, Opera and Safari. https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onscroll#Browser_compatibility – bezbos. Sep 17 '18 at 19:06
  • @SaifTaher I can confirm that the code snippet works on Opera as well. On IE it's broken. – bezbos. Sep 17 '18 at 19:31
  • 1
    Weird I'm using Chrome too... Maybe I didn't implement it correctly, though: I tested it on JS Bin not in a proper HTML file – Saif Taher Sep 17 '18 at 19:50