It enhances user experience by dividing large datasets into manageable pages. Steps to create custom pagination in javascript:
Define Pagination Variables:
let currentPage = 1;
const recordsPerPage = 20; // Adjust as needed
Calculate Total Pages:
Determine the total number of pages based on the dataset length.
const totalPages = Math.ceil(data.length / recordsPerPage);
Display Data for the Current Page:
Extract and display the subset of data corresponding to the current page.
function displayPage(page) {
const startIndex = (page - 1) * recordsPerPage;
const endIndex = startIndex + recordsPerPage;
const paginatedItems = data.slice(startIndex, endIndex);
// Render paginatedItems to the UI
}
Create Navigation Controls:
Implement "Previous" and "Next" buttons to navigate between pages.
function prevPage() {
if (currentPage > 1) {
currentPage--;
displayPage(currentPage);
}
}
function nextPage() {
if (currentPage < totalPages) {
currentPage++;
displayPage(currentPage);
}
}
Initialize Pagination:
Set up the initial page display and attach event listeners to navigation buttons.
document.addEventListener('DOMContentLoaded', () => {
displayPage(currentPage);
document.getElementById('btn_prev').addEventListener('click', prevPage);
document.getElementById('btn_next').addEventListener('click', nextPage);
});