JSFiddle - React, Tailwind, and code Playground
by Prathameshsb
HTML
<h1>
AMAZON TABLE PAGINATION
</h1>
<table id="catTable">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Breed</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
<tr><td colspan="4"><i>Loading...</i></td></tr>
</tbody>
</table>
<button id="prevButton">Previous</button>
<button id="nextButton">Next</button>
CSS
table{
border: 2px solid black;
}
th {
border: 1px solid grey;
}
td, th {
padding: 5px;
}
th {
cursor: pointer;
}
JavaScript
document.addEventListener('DOMContentLoaded', init, false);
let data, table, sortCol;
let sortAsc = false;
const pageSize = 3;
let curPage = 1;
async function init() {
// Select the table (well, tbody)
table = document.querySelector('#catTable tbody');
// get the cats
let resp = await fetch('https://www.raymondcamden.com/.netlify/functions/get-cats');
if(resp.ok){
data = await resp.json();
}else {
console.log('error')
}
renderTable();
// listen for sort clicks
document.querySelector('#nextButton').addEventListener('click', nextPage, false);
document.querySelector('#prevButton').addEventListener('click', previousPage, false);
}
function renderTable() {
// create html
let result = '';
data.filter((row, index) => {
let start = (curPage-1)*pageSize;
let end = curPage*pageSize;
if(index >= start && index < end) return true;
}).forEach(c => {
result += `<tr>
<td>${c.name}</td>
<td>${c.age}</td>
<td>${c.breed}</td>
<td>${c.gender}</td>
</tr>`;
});
table.innerHTML = result;
}
function previousPage() {
if(curPage > 1) curPage--;
renderTable();
}
function nextPage() {
if((curPage * pageSize) < data.length) curPage++;
renderTable();
}