Daniel Garzon
Daniel Garzon

Reputation: 185

Endless Page Rails

Hi guys I have my endless page js code working great but for some reason it only triggers for the second page. I did some changes to some code I found around to meet my needs but now instead of keep loading items it stops in page 2 as my console logs state. Here is my code, can someone please check it and tell me why this isn't triggering? As for my pagination I am using will_paginate gem and I get the links to the pages on the bottom so the back es is working fine. Thank you in advance.

EDIT 2: If someone ever runs into my problem, here is my final setup.

- content_for :scripts do
  :javascript
    (function() {
      var divContainer = $('#posts-container');
      var page = 1,
          loading = false;
      var current_url = divContainer.data('url') + '?page=';

      function nearBottomOfPage() {
        return $(window).scrollTop() >= $(document).height() - $(window).height() - 10;
      }

      $(window).scroll(function(){
        if (loading) {
          return;
        }

        if(nearBottomOfPage()) {
          loading=true;
          page++;
          $.ajax({
            url: current_url + page,
            type: 'get',
            dataType: 'script',
            success: function(html) {
              var $items = $(html).find('.item');
              jQuery(".content").append($items).masonry( 'appended', $items, true );
              $(".content").masonry('reload');
            },
            error: function() {
              console.log("Error")
            },
            complete: function() {
              loading = false;
            }
          });
        }
      });
    }());

EDIT 1:

I found that the nearBottomOfPage() function is not working properly. It only triggers the first time and it never returns true again. Why can this be?

Upvotes: 0

Views: 446

Answers (1)

mu is too short
mu is too short

Reputation: 434685

One thing I notice is that you set your "is loading" flag to true:

if(nearBottomOfPage()) {
  loading=true;

but you never set it back to false. That means that your nearBottomOfPage() check will only be triggered once.

Try updating your AJAX success handler to reset loading:

success: function(html) {
  var $items = $(html).find('.item');
  $(".content").append($items).masonry( 'appended', $items, true );
  $(".content").masonry('reload');
  console.log("Reloaded masonry");
  loading = false; // <----------------------------- This is sort of important.
}

You might want to add an error handler to your AJAX as well. Then you could move the loading = false; to a complete callback:

success: function(html) {
  // As you have it now...
},
error: function() {
  // Complain or something...
},
complete: function() {
  loading = false;
}

Upvotes: 2

Related Questions