---
title: "#114 Endless Page"
author: "CaiDeHen"
date: "2008-12-12T13:50:11Z"
tags: []
slug: "114-endless-page"
draft: false
lastmod: "2008-12-12T13:50:11Z"
id: 291972
url: "https://caidehen.iteye.com/blog/291972"
---

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.

```java
# 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);
```