Home > OS >  Create Pagination in JavaScript with an Array
Create Pagination in JavaScript with an Array

Time:02-01

How could I create a Pagination System in JavaScript? There should be 10 products per page.

I have created an Array of products. I want to loop through all of these products and dsiplay the first 10 products on the first page, and then the next 10 products on the next page.

I have created this Array:

let products = {
    data: [
      {
        productName: "Product1",
      },
      {
        productName: "Product2",
      },
      {
        productName: "Product3",
      },
      {
        productName: "Product4",
      },
      {
        productName: "Product5",
      },
      {
        multiple other products
      },
],
};

I have looped through all of the products and displayed them on screen like this:

for (let i of products.data) {
    let card = document.createElement("div");
    let name = document.createElement("h5");
    container.appendChild(name);
    card.appendChild(container);
    document.getElementById("products").appendChild(card);
}

I want to do this in Vanilla JavaScript

CodePudding user response:

Use the .slice method on the array to to get only a subset of what's within it. .slice(start, end) returns the items in the array starting with <start> and ending with <item before end>.

console.log([0,1,2,3,4,5].slice(2,4));
// returns [2,3]

You'd need additional code and buttons elsewhere on the page to keep track of the start position, but loop would be modified as follows:

for (let i of products.data.slice(start, start   10)) {

CodePudding user response:

I would make an array for each page:

let pages = new Object;

let pageNumber = 1;
for (let i = 0; i < products.data.length; i  ) {

    if(i === 0) {
        pageNumber = 1
    } else {
        pageNumber = Math.ceil(i / 10); 
    }

    if (Array.isArray(pages[`page${pageNumber}`])){
        pages[`page${pageNumber}`].push(products.data[i]);
    } else {
        pages[`page${pageNumber}`] = new Array;
        pages[`page${pageNumber}`].push(products.data[i]);
    }
}

Change this:

for (let i of products.data) {
    ...
}

To this:

function displayPage(pageNumber) {
    for (let i of pages[pageNumber]) {
        ...
    }
}

Then I would run a for loop looping over the pages and making a button for each and displaying it when necessary. I would give each button an onclick that will call the displayPage()

  • Related