.

Friday, August 13, 2010

Endless Automatic Page Scroll from Railscast

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.

Tags: ajax
Download (17.7 MB, 8:43)
alternative download for iPod & Apple TV (11.1 MB, 8:43)
Alternative Solutions
# 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





id="products">
id="loading">Loading more page results...
// 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);

0 comments:

Post a Comment

Facebook Twitter Delicious Digg More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Macys Printable Coupons