Skip to content

Instantly share code, notes, and snippets.

@cpuguy83
Last active December 14, 2015 12:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cpuguy83/5084883 to your computer and use it in GitHub Desktop.
Save cpuguy83/5084883 to your computer and use it in GitHub Desktop.
Endless Scroll with turbolinks support
@EndlessScroll =
load_next: ->
unless (@loading == true) || @next_button().hasClass('disabled')
@loading = true
setTimeout((=>@request()), 50)
active_pager: ->
$('.pagination ul li.active')
next_pager: ->
@active_pager().next('li')
next_button: ->
$('.pagination ul li.next')
prev_button: ->
$('.pagination ul li.previous_page')
url: ->
@next_pager().children('a').first().attr('href')
target: ->
$('.pagination').next('div')
loading: 'false'
success: (res) ->
unless @active_pager().next('li').hasClass('next')
new_pager = @active_pager().next('li')
@active_pager().removeClass('active')
new_pager.addClass('active')
@next_button().addClass('disabled') if @next_button().prev('li').hasClass('active')
@prev_button().removeClass('disabled') unless @prev_button().next('li').hasClass('active')
data = $('<div/>').html(res)
$(@target()).append(data.find("##{@target().attr('id')}").contents())
request: ->
$.ajax
url: @url()
beforeSend: =>
@loading = true
success: (res) =>
@success(res)
complete: =>
@loading = false
@load_next() if @check_scroll() == true
check_scroll: ->
little_window_scroll_ratio = ->
$(document).scrollTop() / $(document).height()
big_window_scroll_ratio = ->
$(window).height() / $(document).height()
window_bigger_than_document = ->
$(window).height() >= $(document).height()
if (little_window_scroll_ratio() >= 0.50) || (big_window_scroll_ratio() >= 0.50) || window_bigger_than_document == true
true
else
false
jQuery ->
triger_endless_scroll = ->
EndlessScroll.load_next() if $('.pagination').length && EndlessScroll.check_scroll() == true
$(document).on 'ready page:load page:restore', -> $('.pagination').hide()
$(document).on 'ready page:load page:change scroll', -> triger_endless_scroll()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment