Skip to content

Instantly share code, notes, and snippets.

@FabianSchmick
Created September 18, 2017 10:01
Show Gist options
  • Save FabianSchmick/c257c1e212d88be079fce808408ff449 to your computer and use it in GitHub Desktop.
Save FabianSchmick/c257c1e212d88be079fce808408ff449 to your computer and use it in GitHub Desktop.
Pagination - Javascript - jQuery
<ul id="listitems" class="list-unstyled">
<li>May</li>
<li>The</li>
<li>Force</li>
<li>Be</li>
<li>With</li>
<li>Foo</li>
</ul>
<ul class="pagination" id="listitems-pagination">
<li><a id="listitems-previous" href="#" class="disabled"><i class="fa fa-angle-double-left" aria-hidden="true"></i> Prev</a></li>
<li><a id="listitems-next" href="#">Next <i class="fa fa-angle-double-right" aria-hidden="true"></i></a></li>
</ul>
function paginate(itemsPerPage) {
var items = jQuery('#listitems'),
pagination = jQuery('#listitems-pagination'),
prevBtn = '#listitems-previous',
nextBtn = '#listitems-next',
currentPage = 1;
var totalPages = Math.ceil(items.children().length / itemsPerPage);
/* Hide all items which come after itemPerPage */
jQuery(items).children(':gt(' + (itemsPerPage * currentPage - 1) + ')').hide();
/* If show previous items was clicked */
pagination.on('click', prevBtn, function () {
currentPage--;
jQuery(nextBtn).removeClass('disabled');
if((currentPage - 1) <= 0){
jQuery(prevBtn).addClass('disabled');
currentPage = 1;
}
items.children().show();
items.children(':gt(' + (itemsPerPage * currentPage - 1) + ')').hide();
items.children(':lt(' + (itemsPerPage * (currentPage - 1)) + ')').hide();
});
/* If show next items was clicked */
pagination.on('click', nextBtn, function () {
currentPage++;
jQuery(prevBtn).removeClass('disabled');
if(currentPage >= totalPages){
jQuery(nextBtn).addClass('disabled');
currentPage = totalPages;
}
items.children().show();
items.children(':gt(' + (itemsPerPage * currentPage - 1) + ')').hide();
items.children(':lt(' + (itemsPerPage * (currentPage - 1)) + ')').hide();
});
}
jQuery(document).ready(function() {
paginate(3);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment