Ana DEV
Ana DEV

Reputation: 1030

Load more posts in a container on scroll with jquery

I am trying to create a nice load more posts feature when scrolling down the page in a div container and when you reach to the end of the container you see more posts. What i tried so far is working but is buggy when i scroll quite fast as it send more ajax requests then needed and is loading duplicated data.

 <!-- HTML Structure -->
 <header style="position:fixed"></header> 
 <section class="page-banner" style="height: 420px;"></section>
 <section class="projects-general">
    <div class="projects-wrapper">
       <div class="projects-list-wrap"></div>
    </div>
 </section>
 <section class="contact-intro"></section>  
 <footer></footer> 
 <!-- HTML Structure -->
 $(window).scroll(function() {
    var pjCount = $('.pj-col').length;
    var totalPj = $('#pj-numb').val();
    if (pjCount >= totalPj){
        return false;
    }else{
        if($(window).scrollTop() >= $('.projects-list-wrap').offset().top + $('.projects-list-wrap').outerHeight() - window.innerHeight + $('header').outerHeight()) {
            jQuery.ajax({
                url: ajaxURL,
                type: "POST",
                beforeSend: function () {
                    $('.projects-wrapper').append("<div class='pj-loader'></div>");
                },
                complete: function () {
                    $('.pj-loader').remove();
                },
                data:{
                    action: "pj_load_more",
                    pjCount:pjCount
                },
                success:function(data){
                    $('.projects-list-wrap').append(data);
                },
                error: function(err){
                    //console.log(err);
                }
            });
        }
    }
});

Any ideas why it is ok when you try to scroll slowly but when like scrolling fast its creating that buggy effect of duplicating posts. Many thanks

Upvotes: 0

Views: 1443

Answers (1)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

Since the ajax call takes time (opposed to my attempt to reproduce) and the scroll event is firing like a machinegun...

The same ajax request could be triggered more than once.

To avoid that, use a flag ajax_request_sent like so:

// A flag to know if a request is sent and the response is not yet received
let ajax_request_sent = false;

$(window).scroll(function() {
  var pjCount = $('.pj-col').length;
  var totalPj = $('#pj-numb').val();
  if (pjCount >= totalPj) {
    return false;
  } else {

    // Use the flag in the condition (so if sent and not yet received == false)
    if (!ajax_request_sent && $(window).scrollTop() >= $('.projects-list-wrap').offset().top + $('.projects-list-wrap').outerHeight() - window.innerHeight + $('header').outerHeight()) {

      // Set the flag to prevent any concurring request
      ajax_request_sent = true
    
      jQuery.ajax({
        url: ajaxURL,
        type: "POST",
        beforeSend: function() {
          $('.projects-wrapper').append("<div class='pj-loader'></div>");
        },
        complete: function() {
          $('.pj-loader').remove();
        },
        data: {
          action: "pj_load_more",
          pjCount: pjCount
        },
        success: function(data) {
          $('.projects-list-wrap').append(data);
          
          // Unset the flag
          ajax_request_sent = false;
        },
        error: function(err) {
          //console.log(err);
        }
      });
      
    }
  }
});

Upvotes: 2

Related Questions