Skip to content

Instantly share code, notes, and snippets.

@beatricebock
Created August 29, 2017 04:23
Show Gist options
  • Save beatricebock/a3ddc68b04a075b26e71c786afaa5f7d to your computer and use it in GitHub Desktop.
Save beatricebock/a3ddc68b04a075b26e71c786afaa5f7d to your computer and use it in GitHub Desktop.
Pagination with jquery
//paginate on load
$('.organization-list').each(function () {
paginate($(this));
$(this).find('.pagination').first().trigger("click"); //paginations won't show the first page if not clicked, so trigger the first click
});
//paginate on list change
$('select.filter').change(
function () {
$parent = $(this).parents('.organization-list');
filter();
paginate($parent);
$(this).parents('.organization-list').find('.pagination').first().trigger("click");
}
);
$('.live-search').keyup(
function(){
$parent = $(this).parents('.organization-list');
live_search();
paginate($(this).parents('.organization-list'));
$(this).parents('.organization-list').find('.pagination').first().trigger("click");
});
function paginate($paginatedList, itemsPerPage)
{
var itemsPerPage = itemsPerPage ? itemsPerPage : 5; //number of items per page
var count = $paginatedList.find('.organization').not(".filtered-out").length; //don't count organizations that have been filteredf out
console.log(count, $paginatedList.find('.filterable').length); //for debugging purposes
var pageCount = count / itemsPerPage; //the number of paginated pages
$paginatedList.find('.pagination-list').empty(); //we don't want multiple generated pagination lists, so remove the current one
for (i = 0; i < pageCount; i++) {
var $pagination = $('<li class="pagination">' + (i+1) + '</li>'); //pagination buttons shouldn't start from 0
$paginatedList.find('.pagination-list').append($pagination); //put each button in a div within the assessed list
$pagination.data('list', $paginatedList); //to make it assessible (you'll see later)
$pagination.on(
{
click:
function page() {
var page = parseInt($(this).text());
var $paginatedList = $(this).data('list');
var from = (page - 1) * itemsPerPage; //we -1'd up there so gotta re-evaulate; this calculates the total number of items
var to = from + itemsPerPage; //
$paginatedList.find('.organization').not('.filtered-out').show(); //don't show the ones that have been .filtered-out
var $visibleOrganizations = $paginatedList.find('.organization').not(".filtered-out").slice(from, to); //we only want to show the organizations on a given page
$paginatedList.find('.organization').not($visibleOrganizations).hide();
$visibleOrganizations.show();
console.log($visibleOrganizations);
$(this).addClass("active");
$(this).siblings().removeClass("active");
}
}
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment