function Pagination(paginatedList, paginationContainer, paginationLimit = 5, listItemTag = "li") {
const createMainPagination = () => {
paginationContainer.innerHTML =
`
`;
}
createMainPagination();
const listItems = paginatedList.querySelectorAll(listItemTag);
const nextButton = paginationContainer.querySelectorAll("#next-button")[0];
const prevButton = paginationContainer.querySelectorAll("#prev-button")[0];
const pageCount = Math.ceil(listItems.length / paginationLimit);
let currentPage = 1;
const disableButton = (button) => {
button.classList.add("disabled");
button.setAttribute("disabled", true);
};
const enableButton = (button) => {
button.classList.remove("disabled");
button.removeAttribute("disabled");
};
const handlePageButtonsStatus = () => {
if (currentPage === 1) {
disableButton(prevButton);
} else {
enableButton(prevButton);
}
if (pageCount === currentPage) {
disableButton(nextButton);
} else {
enableButton(nextButton);
}
};
const handleActivePageNumber = () => {
document.querySelectorAll(".page-item").forEach((button) => {
button.classList.remove("active");
const pageIndex = Number(button.getAttribute("page-index"));
if (pageIndex == currentPage) {
button.classList.add("active");
}
});
};
const appendPageNumber = (index) => {
const pageNumber = document.createElement("li");
pageNumber.classList.add("page-item");
pageNumber.innerHTML = `${index}`;
pageNumber.setAttribute("page-index", index);
pageNumber.setAttribute("aria-label", "Page " + index);
nextButton.parentNode.insertBefore(pageNumber, nextButton);
};
const getPaginationNumbers = () => {
for (let i = 1; i <= pageCount; i++) {
appendPageNumber(i);
}
};
const setCurrentPage = (pageNum) => {
currentPage = pageNum;
if (currentPage < 1 || currentPage > pageCount)
return;
handleActivePageNumber();
handlePageButtonsStatus();
const prevRange = (pageNum - 1) * paginationLimit;
const currRange = pageNum * paginationLimit;
listItems.forEach((item, index) => {
item.classList.add("d-none");
if (index >= prevRange && index < currRange) {
item.classList.remove("d-none");
}
});
};
function init() {
getPaginationNumbers();
setCurrentPage(1);
prevButton.addEventListener("click", (event) => {
event.preventDefault();
setCurrentPage(currentPage - 1);
});
nextButton.addEventListener("click", (event) => {
event.preventDefault();
setCurrentPage(currentPage + 1);
});
document.querySelectorAll(".page-item").forEach((button) => {
const pageIndex = Number(button.getAttribute("page-index"));
if (pageIndex) {
button.childNodes[0].addEventListener("click", (event) => {
event.preventDefault();
if (pageIndex && !button.classList.contains('disabled'))
setCurrentPage(pageIndex);
});
}
});
}
init();
}