Endless scrolling and will_paginate adds the “next page” of items several times

I am following this railscast , trying to implement an endless scroll page in my rails application. When the user scrolls to the bottom of the page, a new set of elements is added, and the page expands, however it is added to the page several times, and the event is fired again on scrolldown, even when all elements in the array are loaded, adding the same set of elements repeatedly several times .

I would like to add a “next page” of elements each time the user scrolls to the bottom and subsequent pages when the user scrolls down again.

Here is jQuery for this function:

jQuery -> if $('.pagination').length $(window).scroll -> url = $('.pagination .next_page').attr('href') if url && $(window).scrollTop() > $(document).height() - $(window).height() - 50 $('.pagination').text('Fetching more products...') $.getScript(url) $(window).scroll() 

and here is the corresponding javascript

 $('#products').append('<%= j render(@products) %>'); <% if @products.next_page %> $('.pagination').replaceWith('<%= j will_paginate(@products) %>'); <% else %> $('.pagination').remove(); <% end %> 
+4
source share
1 answer

Your code will call $.getScript(url) when the user scrolls to 50 pixels from the bottom. Then another call if they scroll to 49px from the bottom. Then another one, if they scroll down to 48px from the bottom, and this will continue until one of the AJAX calls returns and makes the page higher; as soon as the page is higher, you will be outside the 50px zone, and Fetching more products ... will stop.

You want only one getScript at a time. As soon as they move into the 50px zone, you want to get a few more things from the server (only once), and then ignore subsequent scrolling until the server responds.

You have to do something more:

 $(window).scroll -> # Bail out right away if we're busy loading the next chunk. return if(window.pagination_loading) url = $('.pagination .next_page').attr('href') if url && $(window).scrollTop() > $(document).height() - $(window).height() - 50 # Make a note that we're busy loading the next chunk. window.pagination_loading = true # Load as before but attach a callback to clear the flag when we're done. $('.pagination').text('Fetching more products...') $.getScript(url).always -> window.pagination_loading = false 

$.getScript returns jqXHR and jqXHR will always callbacks when the main call to $.ajax .

+6
source

All Articles