I am trying to achieve unlimited scrolling in my rails app using kaminari. Its working as expected but if I move the scrollbar up and down several times its loading again and again until I stop scrolling.
Here is my pagination.js.coffee
$ ->
content = $('#listings') # where to load new content
viewMore = $('#view-more') # tag containing the "View More" link
isLoadingNextPage = false # keep from loading two pages at once
lastLoadAt = null # when you loaded the last page
minTimeBetweenPages = 5000 # milliseconds to wait between loading pages
loadNextPageAt = 10 # pixels above the bottom
waitedLongEnoughBetweenPages = ->
return lastLoadAt == null || new Date() - lastLoadAt > minTimeBetweenPages
approachingBottomOfPage = ->
return $(document).scrollTop() < document.body.offsetHeight - loadNextPageAt
nextPage = ->
url = viewMore.find('a').attr('href')
return if isLoadingNextPage || !url
viewMore.addClass('loading')
isLoadingNextPage = true
lastLoadAt = new Date()
$.ajax({
url: url,
method: 'GET',
dataType: 'script',
success: ->
viewMore.removeClass('loading');
isLoadingNextPage = false;
lastLoadAt = new Date();
})
# watch the scrollbar
$(window).scroll ->
if approachingBottomOfPage() && waitedLongEnoughBetweenPages()
nextPage()
# failsafe in case the user gets to the bottom
# without infinite scrolling taking affect.
viewMore.find('a').click (e) ->
nextPage()
e.preventDefault()
search.html.erb
<div id="listings">
<%= render 'pages/listings' %>
</div>
<% unless @rooms.current_page == @rooms.total_pages %>
<p id="view-more">
<%= link_to('View More', url_for(page: @rooms.current_page + 1)) %>
</p>
<% end %>
search.js.erb
$('#listings').append("<%=j render('pages/listings') %>");
<% if @rooms.current_page == @rooms.total_pages %>
$('#view-more').remove();
<% else %>
$('#view-more a').attr('href', '<%= url_for(page: @rooms.current_page + 1) %>');
<% end %>
Could someone tell me what am doing wrong here?