Created
September 18, 2017 10:01
-
-
Save FabianSchmick/c257c1e212d88be079fce808408ff449 to your computer and use it in GitHub Desktop.
Pagination - Javascript - jQuery
This file contains hidden or 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
<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> |
This file contains hidden or 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
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