raduken
raduken

Reputation: 2119

pagination in javascript showing amount of elements per page

${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

Answers (1)

user3297291
user3297291

Reputation: 23372

Getting the index of the first item on a page

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)
);

Getting the index of the last item on a page

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)
);

Finding out how many pages there are

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)

Writing the actual code

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:

  • Request a page number that is out of range,
  • Request a negative page number
  • Input a 0 or negative page size,
  • etc.

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

Related Questions