handle pagination for too many pages

This commit is contained in:
Corban-Lee Jones 2024-07-11 10:27:34 +01:00
parent a82b505cb1
commit 0d3691b782

View File

@ -18,22 +18,70 @@ function updateTablePagination(pageControlsId, currentPage, pageSize, totalItems
// Calculate amount of pages to account for
const pages = Math.max(Math.ceil(totalItems / pageSize), 1);
// alert(pages + " " + totalItems + " " + pageSize + " ")
const maxVisiblePages = 5;
for (let i = 1; i <= pages; i++) {
let pageItem = $("<li>").addClass("page-item");
let pageLink = $("<button>")
.attr("type", "button")
.attr("data-page", i)
.addClass("page-link page-pick")
.text(i);
let startPage, endPage;
// Insert the new page button before the 'next page' button
pageItem.append(pageLink)
$(`${pageControlsId} .pagination .page-next`).parent().before(pageItem);
if (pages <= maxVisiblePages) {
// If total pages are less than or equal to max visible pages, show all
startPage = 1;
endPage = pages;
} else {
// Determine the start and end pages
const halfVisible = Math.floor(maxVisiblePages / 2);
$(`${pageControlsId} .pagination .page-pick[data-page="${currentPage}"]`).addClass("disabled").attr("tabindex", -1);
if (currentPage <= halfVisible) {
startPage = 1;
endPage = maxVisiblePages;
} else if (currentPage + halfVisible >= pages) {
startPage = pages - maxVisiblePages + 1;
endPage = pages;
} else {
startPage = currentPage - halfVisible;
endPage = currentPage + halfVisible;
}
}
if (startPage > 1) {
addPageButton(pageControlsId, 1);
if (startPage > 2) {
addEllipsis(pageControlsId);
}
}
for (let i = startPage; i <= endPage; i++) {
addPageButton(pageControlsId, i, currentPage);
}
if (endPage < pages) {
if (endPage < pages - 1) {
addEllipsis(pageControlsId);
}
addPageButton(pageControlsId, pages);
}
}
function addPageButton(pageControlsId, pageNumber, currentPage) {
let pageItem = $("<li>").addClass("page-item");
let pageLink = $("<button>")
.attr("type", "button")
.attr("data-page", pageNumber)
.addClass("page-link page-pick")
.text(pageNumber);
if (pageNumber === currentPage) {
pageLink.addClass("disabled").attr("tabindex", -1);
}
pageItem.append(pageLink);
$(`${pageControlsId} .pagination .page-next`).parent().before(pageItem);
}
function addEllipsis(pageControlsId) {
let ellipsisItem = $("<li>").addClass("page-item disabled");
let ellipsisLink = $("<span>").addClass("page-link page-pick").text("...");
ellipsisItem.append(ellipsisLink);
$(`${pageControlsId} .pagination .page-next`).parent().before(ellipsisItem);
}
// Bind the table pagination buttons to control the table pagination