Skip to content

Instantly share code, notes, and snippets.

@benshimmin
Created October 25, 2014 22:55
Show Gist options
  • Save benshimmin/9b07a9d09eba87a2cda9 to your computer and use it in GitHub Desktop.
Save benshimmin/9b07a9d09eba87a2cda9 to your computer and use it in GitHub Desktop.
Clientside pagination in not many lines of code
// If you really need to do pagination clientside (ie. you have
// everything you want to paginate already in the page), then
// with a little jQuery and Underscore it needn't be a big deal.
// Assuming you have a couple of ULs with a bunch of LIs in them
// that you wish to paginate over, let's say one called `users`
// and one called `orders`, then this will do the trick:
(function paginate() {
_.each($("ul.users, ul.orders"), function(ul) {
var $ul = $(ul),
$children = $ul.children("li"),
offset = 0,
perPage = 5;
if ($children.length < perPage) return;
var refresh = function() {
var range = _.range(++offset * perPage, $children.length);
return _.chain($children).map(function(child, i) {
var hide = _.contains(range, i);
$(child)[hide ? "hide" : "show"]();
return hide;
}).last().value();
};
var $more = $("<div>Show more</div>").addClass("more")
.on("click", function() {
!refresh() && $more.hide();
});
$ul.append($more.trigger("click"));
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment