Generate Pagination in JavaScript using an Array of Elements

Is there a way to implement a Pagination System using JavaScript? Specifically, I need to display 10 products per page.

I currently have an Array containing various products and my goal is to iterate through these products to display the first 10 on one page, followed by the next 10 on subsequent pages.

This is the sample Array I am working with:

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

After looping through all the products, I showcase them on screen as shown below:

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

My preference is to achieve this functionality using Vanilla JavaScript

Answer №1

Utilize the .slice function on an array to extract a specific portion of its contents. The syntax for .slice(start, end) allows you to retrieve elements in the array starting at <start> and ending with the element before <end>.

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

To manage the start position efficiently, additional code snippets and buttons can be implemented elsewhere on the webpage, which will necessitate modifying the loop as shown below:

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

Answer №2

To optimize the page display, I suggest creating an array for each individual 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]);
    }
}

Transform this loop code snippet:

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

Into this function:

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

Afterwards, iterate over the pages with a for loop to generate a button for each one and display it when needed. Each button should have an onclick event that triggers the displayPage() function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method for activating the on collapse event with a bootstrap navbar?

I am encountering a common issue with collapsing the navbar on smaller screens and triggering an event when the collapse button icon is clicked. Despite my efforts to find a solution, I have been unsuccessful in using the following JavaScript code: $(&apos ...

Utilize strings as object keys in JavaScript

Let's say I have the following variables: var myKey = "This_is_my_key" var myObj = {"This_is_my_key" : true} What is the proper way to access myObj using the key myKey? ...

Can Java provide functionality similar to JS callbacks?

Can a similar functionality be achieved in Java? function sum(num1, num2, onComplete) { var result = num1 + num2; onComplete(result); } (function(){ sum(3, 5, function(res){alert(res)}); })() Is it possible to implement this in Java without ...

Reload iframe content using a .php file within a different iframe

I am currently working on a page that consists of 7 different iframes: <iframe id="leftframe" src="structure/leftbar.php"></iframe> <iframe id="headerframe" src="structure/header.php"></iframe> <iframe id="menuframe" src="struct ...

Strategies for concealing and revealing content within dynamically loaded AJAX data

I am attempting to show and hide data that is loaded using Ajax. $.ajax({ type: "POST", url: "/swip.php", data: {pid:sldnxtpst,sldnu:sldnu}, success: function(result) { $('.swip').prepend(result); } }); This data gets ...

Troubleshooting event binding problems with jQuery

<div id="parent"> <div id="children"> </div> </div> If we attach the same events to both parent and children elements: $("#parent").live({ mouseenter : Infocus , mouseleave : Outfocus }); $("#childre ...

Trying out the fetch api with Jest in a React Component: A step-by-step guide

As a newcomer to test driven development, I stumbled upon a section that talked about testing/mocking a fetch API. However, I am facing issues while trying to write my own test. In order to practice this concept, I created a simple weather app where I atte ...

What steps can be taken to guarantee that React updates occur in the correct order?

I'm currently working on developing a multi-select dropdown and facing the issue of hiding the options once a user selects one. The problem arises when I try to update the selectedCategoriesData state and then hide the dropdown using setShowCategories ...

Issue with Laravel ReactJs: My changes in the ReactJs file are not being reflected on the website

I've been utilizing Reactjs within Laravel. Recently, I made some modifications to my React Component and upon refreshing my browser, the changes did not reflect. Here are the files involved: resources/views/welcome.blade.php <!doctype html&g ...

In situations where there may be a duplicate, what alternative can I utilize in place of the id attribute?

I understand that almost any element in the DOM can have an "id" attribute, and I've used it to track each client in a table of clients. Although ids should not be repeated, my rows are assigned unique identifiers based on each person's "clientId ...

Exploring the Power of 2D Arrays in JavaScript

Hey there! I'm having trouble defining a 2D array in JS. Two errors are getting in my way and I can't figure out what's going wrong. i is generated by a for loop - it's defined. Even when I try replacing i with 0, the same error occurs. ...

Is there a way for me to access a user control property directly from the client side?

I'm in the process of developing several user controls that will be derived from my base class, BaseControl, which is a subclass of UserControl. The BaseControl class contains important features that I will need to utilize, including a string property ...

Convert a multidimensional array into a string using JavaScript

Currently, I'm in the process of generating an invoice for a collection of books and my intent is to submit it using ajax. However, when attempting to json encode the array of books within the invoice, I am encountering a setback where the value keeps ...

Using AngularJS to encapsulate the JSON response received from the server

Currently, I have a basic CRUD application that is operational. However, I am looking to enhance every response received from the server by adding two additional parameters: 'error' => boolean, 'errorMessage' => string, 'dat ...

Troubleshooting problems with AngularJS placeholders on Internet Explorer 9

On my partial page, I've included a placeholder like this: <input name="name" type="text" placeholder="Enter name" ng-class="{'error':form.name.$invalid}" ng-model="Name" required /> I have also set up client side validation for the ...

Learn the process of seamlessly uploading various document formats, videos, and previewing documents with Angular software

I am having trouble viewing uploaded files in the carousel. While I can see video and image files, other document formats are not displaying. Can someone please recommend a solution to enable viewing all types of documents as well? mydata = [] onSelect ...

No response headers retrieved from WebAPI

Currently, I am utilizing the ASP.NET WebApi in conjunction with a ReactJs application on the front end. In this scenario, I am working on implementing a Get method that enables file downloads from the server. My objective is to configure both the Content- ...

Navigating through a collection of elements

I am currently working on my Stripe Checkout Session, attempting to pass an array of product data to the backend node.js server and iterate over it. The object of products I have is structured like this: { products: [ { _id: '62129d518468 ...

Recalling the layout following the user's computer restart

I am creating a simple online editing tool (similar to Microsoft Outline) for coursework and I would like the outline details to be saved even if the user restarts the system. How can I achieve this? <html> <head> <title>Editor</ ...

Swapping out the video in real-time using an on-demand script

Recently, I encountered an issue with my blog's YouTube video switcher. It seems that the videos won't play once they are changed, and it is related to a light YouTube embed script that I found here: . I believe this script was implemented to imp ...