Last active
December 9, 2015 21:48
-
-
Save markbrown4/4333124 to your computer and use it in GitHub Desktop.
Replaces will_paginate with automatic paging on scroll.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MagicPaginator | |
constructor: (el, options)-> | |
@callback = options.callback || -> false | |
@$el = $(el) | |
@$pagination = @$el.parent().find '.pagination' | |
return if @$pagination.length == 0 | |
@render() | |
$(window).scroll @scrollFetch | |
render: -> | |
@lastPage = @$pagination.find('a:not(.next_page, .previous_page)').last() | |
@currentPage = Number @$pagination.find('em.current').text() | |
@totalPages = Number @lastPage.attr('href').match(/page=(\d+)/)[1] | |
@nextPageUrl = @$pagination.find('a.next_page').attr 'href' | |
@$pagination.html $('<a class="loader btn btn-primary">Read more</a>') | |
@$pagination.find(".loader").click @fetch | |
fetch: => | |
return if @fetching | |
@fetching = true | |
@$pagination.addClass 'loading' | |
$.ajax | |
url: @nextPageUrl, | |
dataType: 'html', | |
headers: | |
Accept: "text/javascript" | |
success: (html)=> | |
@$el.append html | |
@callback() | |
@updateNext() | |
@$pagination.removeClass 'loading' | |
@fetching = false | |
false | |
updateNext: => | |
@currentPage += 1 | |
if @currentPage == @totalPages | |
@$pagination.html '<a href="#" class="top">Back to top ↑</a>' | |
else | |
@nextPage = @currentPage + 1 | |
@nextPageUrl = @nextPageUrl.replace "page=#{@currentPage}", "page=#{@nextPage}" | |
scrollFetch: => | |
if $(window).scrollTop() + $(window).height() + 200 > $(document).height() | |
if @currentPage < @totalPages | |
@fetch() | |
(($)-> | |
$.fn.magicPaginate = (options = {})-> | |
return @each -> | |
new MagicPaginator this, options | |
)(jQuery) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment