DEV Community

Discussion on: A super simple implementation of Infinite Scrolling

Collapse
 
kedzior_io profile image
Artur Kedzior • Edited

Few improvements here:

  1. For the love of whatever you believe in use Typescript. Why would anyone not use Typescript? :-)
  2. This solution kind of works but it will get triggered several times and if you want to fetch stuff from API it will make many unnecessary requests. So how about this:
$(window).on("scroll", function () {
    const scrollHeight = $(document).height() as number;
    const scrollPos = Math.floor($(window).height() + $(window).scrollTop());
    if (scrollHeight === scrollPos) {
        console.log("Scroll MF!");
    }
});
Enter fullscreen mode Exit fullscreen mode

to make it even better, we can make it execute before hitting the bottom and again executing only once:

let page = 1;
let currentscrollHeight: 0;
let lockScroll: false;

$(window).on("scroll", () => {
    const scrollHeight = $(document).height() as number;
    const scrollPos = Math.floor($(window).height() + $(window).scrollTop());
    const isBottom = scrollHeight - 300 < scrollPos;

    if (isBottom && currentscrollHeight < scrollHeight) {

        $.ajax({
            method: "POST",
            url: "/api/search",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ page: this.page })
        } as any)
        .done((posts: Post[]) => {
            this.page = this.page + 1;
            // do whatever
        });

        currentscrollHeight = scrollHeight;
    }
});
Enter fullscreen mode Exit fullscreen mode

Check an example: fullscreen-modal.azurewebsites.net

Collapse
 
jsdgraphics profile image
jsdgraphics

Dude! i made an account here just to thank you men, i spend a whole day trying to make this script work with a custom post type in wordpress, i end up in this article again after close it (i didn't read the comments the first time) and i realize that the main problem for me was "if(((scrollHeight - 300) >= scrollPos) / scrollHeight == 0)".

The script ran like four times every time, i just use your code but with my ajax and bum! thanks a lot good man

Thread Thread
 
kedzior_io profile image
Artur Kedzior

Awesome! I'm glad it helped you!