I am trying to use Kaminari + jQuery to do endless pagination / infinite scrolling. I am trying to append the paginated results (rows) within a table. Unfortunately, the results (row markup) appear above the table. Here's my existing setup:
events_controller.rb
class EventsController < ApplicationController
respond_to :html, :js
def index
@events = Event.all
respond_with(@events)
end
end
events/index.html.erb
<div id="events-container">
<table cellpadding="3" cellspacing="0">
<thead>
...
</thead>
<tbody>
<% if @events.blank? %>
<tr><td> No events yet</td></tr>
<% else %>
<div id="events">
<%= render @events %>
</div>
<% end %>
</tbody>
</table>
<nav class="pagination-container">
<%= paginate @events %>
</nav>
</div>
events/index.js.erb
$('#events').append('<%= j render(@events) %>');
<% if (@events.current_page < @events.num_pages) %>
$('.pagination').replaceWith('<%= j paginate(@events) %>');
<% else %>
$('.pagination-container').remove();
<% end %>
events/_event.html.erb
<tr>
<td><%= event.time %></td>
...
</tr>
<tr>
<td><%= event.location %></td>
...
</tr>
events_endless_paging.js
jQuery(function() {
var isScrolledIntoView;
isScrolledIntoView = function(elem) {
var docViewBottom, docViewTop, elemBottom, elemTop;
docViewTop = $(window).scrollTop();
docViewBottom = docViewTop + $(window).height();
elemTop = $(elem).offset().top;
elemBottom = elemTop + $(elem).height();
return (elemTop >= docViewTop) && (elemTop <= docViewBottom);
};
if ($('.pagination').length) {
$(window).scroll(function() {
var url;
url = $('.pagination .next a').attr('href');
if (url && isScrolledIntoView('.pagination')) {
$('.pagination').text('Fetching more...');
var script = $.getScript(url);
return script;
}
});
return $(window).scroll();
}
});
Everything seems to be wired properly, but what ends up happening is that table rows are inserted between #event-container div and the table. So row styles are all wonky because the tags aren't being properly inserted within the context of a table. I have the feeling that I need to insert table markup within the js response, but am not sure.
I don't think having a div inside the table body is valid.
If you remove the div and append the new rows to the tbody directly you should have more success.
<tbody>
<% if @events.blank? %>
<tr><td> No events yet</td></tr>
<% else %>
<%= render @events %>
<% end %>
</tbody>