Load more WordPress posts on (infinite) scroll with AJAX

I’m currently loading more posts via AJAX when the user clicks on a ‘load more’ button. The code I’m using is based on this tutorial:

http://www.problogdesign.com/wordpress/load-next-wordpress-posts-with-ajax/

Read More

My aim is to modify that code so that more posts are loaded when a user scrolls to the bottom of the page. I’ve tried replacing

$('#pbd-alp-load-posts a').click(function() {

});

with this:

$(window).scroll(function(){
    if ($(window).scrollTop() == $(document).height() - $(window).height()){

    }
});

When doing that, new posts are loaded successfully but when the user scrolls to the bottom of the browser window a second time, the next set of posts are not loaded into the page.

Using the button click approach, a new ‘load more’ button is added to the page so the next set of posts are loaded if a user clicks again. How can I get my scroll approach to load the next set of posts when the user scrolls to the bottom of the page again?

Related posts

Leave a Reply

2 comments

  1. In your test, instead of using an exact equality :

    if ($(window).scrollTop() == $(document).height() - $(window).height()) {
        ...
    }
    

    try using a threshold, e.g. :

    if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
        ...
    }
    
  2. hey sorry about my english
    try this

     $(window).scroll(function() { //detect page scroll
        if($(window).scrollTop() + $(window).height() == $(document).height())
        {
            $('#pbd-alp-load-posts a').trigger('click');
        }});
    

    put it above

    $('#pbd-alp-load-posts a').click(function() 
    

    that code force button #pbd-alp-load-posts a when scroll right over the end to be clicked
    it’s work fine