Ever wondered how some sites seem to have endless scrolling page with no pagination? Find out how easy it is to do this in Rails in this episode.
# products_controller.rb
def index
@products = Product.paginate(:page => params[:page], :per_page => 15)
end
# index.js.rjs
page.insert_html :bottom, :products, :partial => @products
if @products.total_pages > @products.current_page
page.call 'checkScroll'
else
page[:loading].hide
end
# application_helper.rb
def javascript(*args)
content_for(:head) { javascript_include_tag(*args) }
end
<!-- index.html.erb -->
<% title "Products" %>
<% javascript :defaults, 'endless_page' %>
<div id="products">
<%= render :partial => @products %>
</div>
<p id="loading">Loading more page results...</p>
// endless_page.js
var currentPage = 1;
function checkScroll() {
if (nearBottomOfPage()) {
currentPage++;
new Ajax.Request('/products.js?page=' + currentPage, {asynchronous:true, evalScripts:true, method:'get'});
} else {
setTimeout("checkScroll()", 250);
}
}
function nearBottomOfPage() {
return scrollDistanceFromBottom() < 150;
}
function scrollDistanceFromBottom(argument) {
return pageHeight() - (window.pageYOffset + self.innerHeight);
}
function pageHeight() {
return Math.max(document.body.scrollHeight, document.body.offsetHeight);
}
document.observe('dom:loaded', checkScroll);