I created a form with a hidden field called ‘page’ in my div where I want infinite scrolling to happen. Then I set up my controller action for the action in the normal way with pagination by kaminari:
def campaign
@testimonials = Testimonial.page(params[:page])
respond_to do |format|
format.js
format.html
end
end
In campaign.js.erb I simply append the new results to the bottom of the div.
The last bit is to write some coffeescript that increments the page field and submits the form when you scroll to the bottom of the div:
loading = false
$('.testimonials').scroll ->
if $(@).scrollTop() + $(@).innerHeight() >= $(@)[0].scrollHeight
unless loading == true
loading = true
page = parseInt($(@).find('#page').val())
page++
$(@).find('#page').val(page)
$(@).find('form').submit()
loading = false
Oh, yeah, the page field needs to start out with a value of 1.
Bam. Easy infinite scrolling in a div.
If you enjoyed this post, make sure you subscribe to my RSS feed!




5 responses so far ↓
1 mileszs // Nov 19, 2012 at 7:45 pm
Nice!
Also, what’s with the code-formatting? It is not formatted at all, for me. Decipherable, but frustrating.
2 David Christiansen // Nov 19, 2012 at 9:26 pm
I know. I should fix that.
3 David Christiansen // Nov 19, 2012 at 9:30 pm
Code formatting fixed.
4 Paul Pettengill // May 7, 2013 at 1:51 pm
Can you show the view as well? I’m trying to mimic your approach, but I’m not sure I have it down completely.
5 David Christiansen // May 7, 2013 at 7:34 pm
Oh man. I wish. I can’t even remember where I did that now… Sorry!
Leave a Comment