Skip to content

Instantly share code, notes, and snippets.

@levymetal
Last active November 1, 2022 02:36
Show Gist options
  • Save levymetal/5083753 to your computer and use it in GitHub Desktop.
Save levymetal/5083753 to your computer and use it in GitHub Desktop.
Tutorial on how to create infinite scroll with Rails @ jQuery, full post @ http://christianvarga.com/blog/2013/02/simple-infinite-scroll-with-rails-and-jquery/
- posts.each do |post|
.post
= post.content
//= require jquery.inview.min.js
gem 'will_paginate', '~> 3.1.0'
.posts
= render :partial => 'shared/posts', :locals => { :posts => @posts }
= link_to 'Load More Posts', posts_path(:page => @posts.next_page), :class => 'load-more-posts', :remote => true if @posts.next_page
$('.posts').append('#{escape_javascript(render partial: "shared/posts", :locals => { :posts => @posts })}');
$('a.load-more-posts').attr('href', '#{posts_path page: @posts.next_page}');
- unless @posts.next_page
$('a.load-more-posts').remove();
class Post < ActiveRecord::Base
...
self.per_page = 10
...
end
# if you aren't using turbolinks, replace the following line with `$ ->`
$(document).on 'turbolinks:load', ->
loading_posts = false
$('a.load-more-posts').on 'inview', (e, visible) ->
return if loading_posts or not visible
loading_posts = true
$.getScript $(this).attr('href'), ->
loading_posts = false
class PostsController < ApplicationController
def index
@posts = Post.paginate(:page => params[:page]) # replaces Post.all
respond_to do |format|
format.html
format.js # add this line for your js template
end
end
def home
@posts = Post.where(:user_id => current_user.id).paginate(:page => params[:page])
...
end
...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment