Skip to content

Instantly share code, notes, and snippets.

@DylanFM
Created February 28, 2011 04:26
Show Gist options
  • Save DylanFM/846931 to your computer and use it in GitHub Desktop.
Save DylanFM/846931 to your computer and use it in GitHub Desktop.
Works with will_paginate. Requires innerShiv http://jdbartlett.github.com/innershiv/
$.fn.extend
paginate: (opts) ->
# If we are working on elements
if this.length
this.each ->
defaults =
pagination: '.pagination'
itemPlural: 'things'
num: 30
opts = $.extend {}, defaults, opts
# Points to the list being paginated
list = $ this
# Get the pagination
pagination = $ opts.pagination
# Confirm everything is OK to proceed
if pagination.length and list.length
# Find the next page's link
next_url = pagination.find('em').next('a').attr 'href'
if next_url
# The more link should link to the next page
more = $ """
<a href="#{next_url}" title="Load more #{opts.itemPlural}" class="load-more">More</a>
"""
# Setup the AJAX stuff
more.click (e) ->
link = $ @
url = link.attr 'href'
# Loading link
link.addClass('loading').text 'Loading'
e.preventDefault()
# Fetch the URL via AJAX and append the contents to the list
$.get url, { format: 'partial' }, ((data, status) ->
if data
# Add the new items
list.append innerShiv(data, false)
# Ratemate again
ST.utilities.ratemate()
# More should point to the next page or no page if there aren't any more items
if $(data).filter('li').length < opts.num # There are less than there should be in the response
# We don't need to link to any more
link.hide()
else
# Not loading
link.removeClass('loading').text 'More'
# Add 1 to the page parameter
num = parseInt url.match(/page=(\d+)/i)[1], 10
# And point the more link to the next page
link.attr 'href', url.replace(/page=(\d+)/i, "page=#{num + 1}")
), 'html'
# Replace the pagination with the more link
pagination.replaceWith more
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment