skip to Main Content

I am trying to load a function when the user has scrolled 100px past the top of the site footer, the function is to load some additional page content. So I have the following script:

$(window).on(‘scroll’, function () {
if ($(window).scrollTop() + $(window).height() >= $(‘#footer’).height() – 100) {
load_posts();
}
});

However, the function is running multiple times, and using console.log I have discovered that the load_posts() function is actually running once for every pixel passed that 100px, i.e. if I scroll 105px in the footer it loads 5 times, so additional content is loaded 5 times.

How do I get the function only to load once? So that the user can see the new content then continue to scroll down to load the next further content? Perhaps a timeout before it loads, so that the first lot of additional content has time to load before it runs a second time and therefore the user is no longer in the footer?

2

Answers


  1. Chosen as BEST ANSWER

    Got this working with the following:

    $(window).on('scroll', function(){
        if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
            if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
                    load_posts();
            }
        }
    });
    

    Taken from here: https://silvawebdesigns.com/load-more-posts-ajax-button-in-wordpress/


  2. There is a small trick you can use for this problem: it works on my machine.

    Use:

    <!DOCTYPE html>
    

    at the top of your html.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search