skip to Main Content

I have 20 items in total, per page 5 items

How to calculate the page number if know id of item in general using javascript.

Possible formula or way to calculate the page number by id value

example:

let itemsTotal = 20;
let perPage = 5;
let itemId=25;
let pageForThisProduct = Math.ceil(itemId/itemsTotal);

2

Answers


  1. You’re close. You don’t divide the current item in the list by the number of items – you divide the current item by the number of items allowed per page (or limit).

    function getPageNum(item, limit = 5) {
      return Math.ceil(item / limit);
    }
    
    console.log(`Item 1 is on page ${getPageNum(1)}`);
    console.log(`Item 5 is on page ${getPageNum(5)}`);
    console.log(`Item 7 is on page ${getPageNum(7)}`);
    console.log(`Item 10 is on page ${getPageNum(10)}`);
    console.log(`Item 13 is on page ${getPageNum(13)}`);
    console.log(`Item 15 is on page ${getPageNum(15)}`);
    console.log(`Item 16 is on page ${getPageNum(16)}`);
    console.log(`Item 20 is on page ${getPageNum(20)}`);
    console.log(`Item 21 is on page ${getPageNum(21)}`);
    Login or Signup to reply.
  2. You can use the following code to get the page number based on ID:

    let itemsTotal = 20;
    let perPage = 5;
    let itemId = 25;
    let pageForThisProduct = Math.ceil(itemId / perPage);
    

    The variable pageForThisProduct will store the page number and you can display based on your functionality.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search