Show Pagination of Items on the Screen

I am dealing with an Array of Objects:

const myArray = [
    {myObject: "1"},
    {myObject: "2"},
    {myObject: "3"},
    {myObject: "4"},
    {myObject: "5"},
]

To implement a pagination system for these Objects, I have come up with the following code:

function paginateData (items, currentPage, itemsPerPage) {
    let offset = (currentPage - 1) * itemsPerPage;
    let paginatedItems = items.slice(offset).slice(0, itemsPerPage);
    let total_pages = Math.ceil(items.length / itemsPerPage);

    return {
        currentPage: currentPage,
        itemsPerPage: itemsPerPage,
        previousPage: currentPage - 1 ? currentPage - 1 : null,
        nextPage: (total_pages > currentPage) ? currentPage + 1 : null,
        totalItems: items.length,
        totalPages: total_pages,
        data: paginatedItems
    };
}

After successfully logging the results to the console, I now aim to display each object in myArray using this pagination system. How can I achieve this effectively?

I have attempted to utilize the append and append child functions for displaying the objects on screen. Despite watching various videos and reading articles, I have yet to find a solution.

In addition to the next and previous buttons, I also wish to include numbered buttons on the screen. These buttons should display the page number and lead to the corresponding page when clicked.

This is the code snippet I have been working on:

let products = [
    productName: "Brand Name",
    category: "category",
    price: "30",
    image: "images/main_img.jpg",
  },
]
function createProductCards(products) {
  for (let item of products) {
    //Create Card
    const card = document.createElement("div");
    card.classList.add("card", item.category);//Card has category and starts hidden
    //Image container
    const imgContainer = document.createElement("div");
    imgContainer.classList.add("image-container");
    //Image tag
    const image = document.createElement("img");
    image.setAttribute("src", item.image);
    imgContainer.appendChild(image);
    card.appendChild(imgContainer);
    //Info container
    const infoContainer = document.createElement("div");
    infoContainer.classList.add("container");
    //Product name
    const name = document.createElement("h5");
    name.classList.add("product-name");
    name.innerText = item.productName.toUpperCase();
    infoContainer.appendChild(name);
    //Price
    const price = document.createElement("h6");
    price.innerText = "$" + item.price;
    infoContainer.appendChild(price);

    card.appendChild(infoContainer);
    document.getElementById("products").appendChild(card);
    }
}

Answer №1

Discussing the solution to nul->null

I believe this approach will be beneficial for you

The code is quite straightforward

const paginator = (items, page, per_page) => {
  let offset = (page - 1) * per_page;
  let paginatedItems = items.slice(offset).slice(0, per_page);
  let total_pages = Math.ceil(items.length / per_page);

  return {
    page: page,
    per_page: per_page,
    pre_page: page - 1 ? page - 1 : null,
    next_page: (total_pages > page) ? page + 1 : null,
    total: items.length,
    total_pages: total_pages,
    data: paginatedItems
  };
};
const createCard = item => `<div class="card ${item.category}">
  <div class="image-container"><img src="${item.image}" /></div>
  <div class="container">
    <h5 class="product-name">${item.productName.toUpperCase()}</h5>
    <h6>$${item.price}</h6>
  </div>
</div>`;

window.addEventListener("DOMContentLoaded", () => {
  const productContainer = document.getElementById("products");
  const buttonContainer = document.getElementById("buttons");
  const prev = document.getElementById("prev");
  const next = document.getElementById("next");
  let currentPage = 1;
  const perPage = 2;
  const lastPage = Math.floor(products.length / perPage) + 1;
  document.getElementById("nav").addEventListener("click", (e) => {
    const tgt = e.target;
    if (["prev", "next"].includes(tgt.id)) {
      const dir = e.target.id === "next" ? 1 : -1;
      currentPage += dir;
      if (currentPage < 1) currentPage = 1;
      if (currentPage >= lastPage) currentPage = lastPage;
    } else {
      currentPage = +tgt.textContent;
    }
    prev.disabled = currentPage === 1;
    next.disabled = currentPage === lastPage;
    buttonContainer.querySelectorAll('button')
      .forEach((button, i) => button.classList.toggle('active', i === currentPage - 1)); // currentPage starts from 1, i starts from 0
    productContainer.innerHTML = paginator(products, currentPage, perPage)
      .data.map(item => createCard(item)).join("");
  });
  buttonContainer.innerHTML = Array.from({
      length: lastPage
    })
    .map((_, i) => `<button type="button">${i+1}</button>`).join("");
  prev.click(); // start
});
.active {
  font-weight: bold;
}

.card { padding: 5px; width: 80vw; border: 1px dotted black; } 
.image-container { border: 3px solid black; width:100px; height:100px; }
.category1 { background-color: teal; }
.category2 { background-color: yellow; }
.category3 { background-color: pink; }
<nav id="nav">
  <button type="button" id="prev">Prev</button>
  <span id="buttons"></span>
  <button type="button" id="next">Next</button>
</nav>
<hr/>
<div id="products"></div>


<script>
  // test data 
  const products = [{
      productName: "Brand Name 1",
      category: "category1",
      price: "30",
      image: "https://dummyimage.com/100x100/fff/000.png&text=Product+1"
    },
    {
      productName: "Brand Name 2",
      category: "category1",
      price: "40",
      image: "https://dummyimage.com/100x100/fff/000.png&text=Product+2"
    },
    {
      productName: "Brand Name 3",
      category: "category1",
      price: "50",
      image: "https://dummyimage.com/100x100/fff/000.png&text=Product+3"
    },
    {
      productName: "Brand Name 4",
      category: "category2",
      price: "60",
      image: "https://dummyimage.com/100x100/fff/000.png&text=Product+4"
    },
    {
      productName: "Brand Name 5",
      category: "category2",
      price: "70",
      image: "https://dummyimage.com/100x100/fff/000.png&text=Product+5"
    },
    {
      productName: "Brand Name 6",
      category: "category3",
      price: "80",
      image: "https://dummyimage.com/100x100/fff/000.png&text=Product+6"
    },
    {
      productName: "Brand Name 7",
      category: "category3",
      price: "90",
      image: "https://dummyimage.com/100x100/fff/000.png&text=Product+7"
    }
  ];
</script>

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

Contrasting actions observed when employing drag functionality with arrays of numbers versus arrays of objects

Being a newcomer to D3 and JavaScript, I'm hoping someone can help me clarify this simple point. I am creating a scatter graph with draggable points using code that closely resembles the solution provided in this Stack Overflow question. When I const ...

What is the best way to position a tooltip near an element for optimal visibility?

One div is located on the page as follows: <div id="tip"> Text for tip goes here... </div> And another one can be found below: <div class="element"> Text for element goes here... </div> There is also a piece of JavaScript ...

Steps for showing retrieved data individually:

Currently, I am utilizing angular-js, JavaScript, and HTML in my project. I have successfully retrieved a list of customer names and their corresponding details from the database. However, I am looking to implement a feature where each record is displayed ...

JavaScript conditional substring manipulation

I am working on a function that is designed to clean strings, specifically two types of strings: "SATISFACTION._IS1.TOUTES_SITUATIONS.current_month_note" and "SATISFACTION._IS1.TOUTES_SITUATIONS.note". PS Just to clarify, TOUTES_SITUATIONS is a variable. ...

Get the HTML source code for a form that has been created using AngularJS

Can AngularJS be used to download a portion of code generated by a form? Insert the following code snippet: http://jsbin.com/nufixiwali/edit?html,js,output I am looking to generate an .html file that only includes the code generated after the html tag. ...

Live search feature for multiple input fields using jQuery for an array of elements

I am currently trying to implement a jQuery live search feature for multiple input fields. The live search works perfectly fine with just one input field (without an array), but when using multiple search fields with an array, nothing seems to happen. ...

Having several jQuery Ajax requests in a Backbone application causes confusion in the data

Currently, I am working on a Backbone application that utilizes a collection to manage data sources. Each time a new data source is added, its model is included in the collection and a jQuery Ajax call is triggered as follows: fetch: function() { ...

The complexities of stopPropagation() causing further confusion

I have encountered an issue with my code. It currently allows a dropdown functionality for a <ul> element, but when a child <li> is clicked, it also closes other menus of the same type. To fix this, I used an if clause to check if the clicked ...

Weak Password Alert

After spending hours writing code for form validation and password strength checking, I encountered a roadblock. The form validates successfully, but the password strength indicator is not updating as expected. Despite double-checking the logic in my code ...

The efficiency of a for loop in Javascript can be influenced by the way the loop

I experimented with three different for loop cases in JavaScript, each performing a seemingly useless action 1000000000 times. Surprisingly, the speed of these codes varied from one another. Initially, I suspected that the difference in performance could ...

Eliminate HTML tags and formatting, but retain the anchor tags within the string

I have a string variable with HTML content that I need to clean up by removing all tags and formatting, while still preserving anchor tags for clickable links. content = "<div><a href=\"1\">I</a> was going here and then <a h ...

Tips on containing the reach of a function in JavaScript/jQuery

I have a scenario where I have multiple .js files linked on the page, each containing functions with the same name. For example: first.js function DisplayContent(data,$target) // data is string { $target.html('<span>'+ data +'&l ...

The React application is showing an empty page without any visible errors during the compilation process

I'm having trouble with my React app - it compiles without errors but only shows a blank page. Can someone help me figure out what's wrong with my code? I'm new to React and could use some guidance. index.js import React from 'react&ap ...

Exploring Linked Data in JSON API Response with Rails API, Active Model Serializer, and Vue.js Single Page Application

I am working with data structured in a tree/hierarchical model for climbing areas, where they are connected through parent and child relationships. By utilizing the JSON API adapter along with my Active Model Serializer, class AreaSerializer < ActiveM ...

Examining Resolver Functionality within NestJS

Today I am diving into the world of writing tests for NestJs resolvers. I have already written tests for my services, but now it's time to tackle testing resolvers. However, I realized that there is a lack of documentation on testing resolvers in the ...

The Toggle Functionality necessitates a double-click action

I'm currently working on implementing a menu that appears when scrolling. The menu consists of two <li> elements and has toggle functionality. Everything is functioning properly, except for the fact that the toggle requires two taps to activate ...

Using JavaScript to Filter Through Numerous Values Based on Different Attributes

My goal is to efficiently filter multiple attributes with multiple values 'arr' represents a list of all products, and 'f_...' indicates the attribute such as color or type. 'namet' denotes the selected attribute by the user ...

The event handling mechanism in React JS for elements coming into view

Can someone please guide me on implementing the inview event in React JS? I want to achieve something like this: <div inview={handleInView}></div> I specifically need to add it to the Footer section so I can dynamically load more news a ...

Is my approach to passing structures by reference incorrect?

#include<stdio.h> struct mystruct{ int age; //age of child int flag; //flag: if 1 then change the age, if 0 then don't }; /////////////////////////////////////////////////////////////////////////// ...

Error: Unable to locate Vue and its definition

Currently in the process of revamping my portfolio and transitioning it to Vue. This marks my second endeavor with Vue, however, I'm encountering an issue where I continuously receive an error stating that Vue is not defined in my main.js file (which ...