Reputation: 2119
${totalItems} = 22 ${pageSize} = 10
I would like to know how can I create a calculation.
like that: first will show 1 - 10 items, if i click in the next page will show: 11 - 20 and the last one will be 21 - 22.
so basically the calculation will be showing the numbers 1 -10 then 11-20 everytime i click in the next page in my pagination.
can someone give a javascript sample for this? the only value I have is 22, so I would like do a calculation like I said above. and display this in my html.
Upvotes: 0
Views: 15832
Reputation: 23372
To get the first index of a page, you multiple the current page number by the number of items per page:
firstIndex = pageSize * pageNr
For your example:
console.log(
"Start of each page:",
[0, 1, 2].map(pageNr => 10 * pageNr)
);
To get the index of the last item in a page, we can use this function to get the starting index of the next page, and subtract 1
:
lastIndex = pageSize * (pageNr + 1) - 1
console.log(
"End of each page:",
[0, 1, 2].map(pageNr => 10 * (pageNr + 1) - 1)
);
To see how many pages we need to render all our items, we divide the total number of items by the page size and round upwards using Math.ceil
:
nrOfPages = Math.ceil(nrOfItems / pageSize)
Now that we've got the basic "math" covered, we can start writing actual functions and create a small app.
Depending on the format of the data, you can build some safety checks to make sure you cannot:
0
or negative page size,Since you haven't provided anything useful to work with, I'm going to skip these measures and show you an example based on one array of items to paginate:
function getPageStart(pageSize, pageNr) {
return pageSize * pageNr;
};
function getPageLabel(total, pageSize, pageNr) {
const start = Math.max(
getPageStart(pageSize, pageNr),
0
);
const end = Math.min(
getPageStart(pageSize, pageNr + 1),
total
);
return `${start + 1} - ${end}`;
}
const itemsToShow = Array.from({ length: 22 }, (_, i) => `Item ${i + 1}`);
const size = 10;
const pages = Array.from(
{ length: Math.ceil(itemsToShow.length / size) },
(_, i) => getPageLabel(itemsToShow.length, size, i)
)
console.log(pages);
Upvotes: 11