Steps for Implementing a "Load More" Button on an HTML JSON Page

I'm currently engaged in a project that involves fetching product information from a JSON file and displaying it on an HTML page using JavaScript. While I've successfully implemented the fetch function, I now want to add a "Load More" function/button. The goal is to initially show 12 items (in a 4x3 grid) on the page and then load an additional 12 items when the user clicks the button. Any assistance with this task would be greatly appreciated. Currently, the code displays all data from the JSON file, but I wish to modify it to only display the first 12 items and load more upon user interaction. The code snippet below represents a section of the JSON file.



`{ "productList": [
    {
        "images": [
            "//assetsprx.matchesfashion.com/img/product/1454160_1_medium.jpg",
            "//assetsprx.matchesfashion.com/img/product/1454160_2_medium.jpg",
            "//assetsprx.matchesfashion.com/img/product/1454160_3_medium.jpg",
            "//assetsprx.matchesfashion.com/img/product/1454160_4_medium.jpg",
            "//assetsprx.matchesfashion.com/img/product/1454160_5_medium.jpg",
            "//assetsprx.matchesfashion.com/img/product/1454160_6_medium.jpg"
        ],
        "name": "Fringed checked wool-blend coat",
        "designer": "Marni",
        "url": "/products/Marni-Fringed-checked-wool-blend-coat-1454160",
        "price": "£1,790",
        "index": 0,
        "code": "1454160"
    },
    {
        "images": [
            "//assetsprx.matchesfashion.com/img/product/1454112_1_medium.jpg",
            "//assetsprx.matchesfashion.com/img/product/1454112_2_medium.jpg",
            "//assetsprx.matchesfashion.com/img/product/1454112_3_medium.jpg",
            "//assetsprx.matchesfashion.com/img/product/1454112_4_medium.jpg",
            "//assetsprx.matchesfashion.com/img/product/1454112_5_medium.jpg",
            "//assetsprx.matchesfashion.com/img/product/1454112_6_medium.jpg"
        ],
        "name": "Shopping logo-jacquard tote bag & leather pouch",
        "designer": "Marni",
        "url": "/products/Marni-Shopping-logo-jacquard-tote-bag-%26-leather-pouch-1454112",
        "price": "£890",
        "index": 1,
        "code": "1454112"
    },
    {
        "images": [
            "//assetsprx.matchesfashion.com/img/product/1454159_1_medium.jpg",
            "//assetsprx.matchesfashion.com/img/product/1454159_2_medium.jpg",
            "//assetsprx.matchesfashion.com/img/product/1454159_3_medium.jpg",
            "//assetsprx.matchesfashion.com/img/product/1454159_4_medium.jpg",
            "//assetsprx.matchesfashion.com/img/product/1454159_5_medium.jpg",
            "//assetsprx.matchesfashion.com/img/product/1454159_6_medium.jpg"
        ],
        "name": "Suede and silk-knit midi skirt",
        "designer": "Marni",
        "url": "/products/Marni-Suede-and-silk-knit-midi-skirt-1454159",
        "price": "£1,690",
        "index": 2,
        "code": "1454159"
    },

fetch("products/products.json")
  .then((response) => response.json())
  .then((data) => {
    console.log(data);
    for (var i = 0; i < data.productList.length; i++) {
      console.log(data.productList[i].images);

   
      products =
        products +
        `
      <div class=card>
      <img src="${data.productList[i].images[2]}">
      <h4>${data.productList[i].designer}</h4>
      <p>${data.productList[i].name}</p>
      <p>${data.productList[i].price}</p>


      </div>
      
      `;
    }
    document.querySelector("#myData").innerHTML = products;
    
  }
  );
html,
body {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
  left: 0;
  top: 0;
  font-size: 100%;
}

html {
  box-sizing: border-box;
  font-size: 62.5%;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

/* FONT & TYPOGRAPHY STYLES */

p,
h1,
h2,
h3,
h4,
body,
html,
label {
  font-family: "Lato", Helvetica, sans-serif;
  color: #333447;
  line-height: 1;
}
h1 {
  font-size: 2.5rem;
}
h2 {
  font-size: 2rem;
}
h3 {
  font-size: 1.375rem;
}
h4 {
  font-size: 1.125rem;
}
p {
  font-size: 1.125rem;
  font-weight: 300;
}
strong {
  font-weight: 700;
}

/* button */
.btncontainer {
  display: flex;
  justify-content: center;
}
button {
  background-color: #000; /* Green */
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  cursor: pointer;
  font-family: "Lato", Helvetica, sans-serif;
}
button:hover {
  background-color: #fff;
  color: #000;
  border: #000 solid 1px;
}

/* CLASSES */
.product-img {
  max-width: 90%;
}

/* GRID SYSTEM  */

.container {
  margin-bottom: 2rem;
  margin-top: 2rem;
}

.row {
  display: flex;
  justify-content: space-between;
  text-align: center;
}
#myData {
  display: grid;

  grid-gap: 20px;
  padding: 20px;
}

 
 



@media (min-width: 768px) {
  #myData {
    grid-gap: 20px;

    grid-template-columns: repeat(2, 1fr);
  }
}

@media (min-width: 960px) {
  #myData {
    grid-gap: 20px;

    grid-template-columns: repeat(3, 1fr);
  }
}

@media (min-width: 1200px) {
  #myData {
    grid-gap: 20px;

    grid-template-columns: repeat(4, 1fr);
  }
}
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Product List Front End Test</title>
    <link rel="stylesheet" href="css/style.css" />
    <link rel="shortcut icon" href="#" />
  </head>
  <body>
    <main class="container">
      <section class="row">
        <div clas="col-6">
          <h1>Product List Page Test by ______</h1>
        </div>
      </section>
      <section class="row" id="productList">
        <div id="myData"></div>
      </section>
      <div class="btncontainer">
        <button id="lmbutton">Load more</button>
      </div>
    </main>
    <script src="js/main.js"></script>
  </body>
</html>

Answer №1

Almost there! Instead of calling a variable, make sure you call a function after html events. Wrap your JavaScript code in a function and then call it.

function loadMore() {
  fetch("products/products.json")
    .then((response) => response.json())
    .then((data) => {
      console.log(data);
      for (var i = 0; i < data.productList.length; i++) {
        console.log(data.productList[i].images);

        //   if (i <= 11) {
        products =
          products +
          `
      <div class=card>
      <img src="${data.productList[i].images[2]}">
      <h4>${data.productList[i].designer}</h4>
      <p>${data.productList[i].name}</p>
      <p>${data.productList[i].price}</p>


      </div>
      
      `;
      }
      document.querySelector("#myData").innerHTML = products;
      // }
    });
}
@import url(https://fonts.googleapis.com/css?family=Lato:400,300,700);

/* UNIVERSAL */
html,
body {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
  left: 0;
  top: 0;
  font-size: 100%;
}

html {
  box-sizing: border-box;
  font-size: 62.5%;
}
*:before,
*:after {
  box-sizing: inherit;
}
...
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>Product List Front End Test</title>
  <link rel="stylesheet" href="css/style.css" />
  <link rel="shortcut icon" href="#" />
</head>

<body>
  <main class="container">
    <section class="row">
      <div clas="col-6">
        <h1>Product List Page Test by ______</h1>
      </div>
    </section>
    <section class="row" id="productList">
      <div id="myData"></div>
    </section>
    <div class="btncontainer">
      <button id="lmbutton" onclick="loadMore();">Load more</button>
    </div>
  </main>
  <script src="js/main.js"></script>
</body>

</html>
You might notice I put a (); after the function call, this is not necessary, with zero parameters and no semicolon it still calls, but since the onload essentially creates a new javaScript context, it would be best practice

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

Extract data from a JSON file containing only the root element on an Android device

I'm looking to extract JSON data from The Movie Database in a specific structure: [ { "iso_3166_1": "AD", "english_name": "Andorra" }, { "iso_3166_1": "AE", "english_name": "United Arab Emirates" }, This is the API servic ...

What could be the reason behind the failure of my inner div to successfully implement the flex-row

I'm currently trying to position two divs next to each other horizontally, and my concept was to utilize flexbox, but including the property flex-row doesn't seem to yield any results and I can't comprehend the reason behind it. How can I a ...

Using vue-select: In VueJs, how to pass an option slot from a grandparent component

Utilizing a custom dropdown component called 'vue-select', there is an option to customize the options view using slots as detailed in this documentation -> https://vue-select.org/guide/slots.html I am aiming to achieve a similar customizatio ...

Is it possible to refresh a div on one .aspx page using content from another .aspx page?

Just beginning my journey with asp.net and currently tackling a project that involves two .aspx pages. Events.aspx: This page is where the site admin can update upcoming events and webinars using an available panel to input event title, date, information ...

The Camera component in React Native is not currently supporting foreground service

Trying to capture images in a foreground service, such as taking pictures while the user is using another app. Everything works fine within the app, but when the app is closed with the foreground service active, the camera stops working and shows this erro ...

When an attempt to make a POST request using fetch() is made, a TypeError: Failed to fetch error is immediately thrown instead of

My front-end form is posting data using the fetch() function. Everything works fine and I get the correct response from the server when it runs smoothly without any interruptions. However, when I debug the server endpoint, it throws a TypeError: failed to ...

managing array of JSON responses

Received a JSON response from the backend: { "json": { "response": { "servicetype": "1", "functiontype": "10011", "statuscode": "0", "statusmessage": "Success", "data":{ "roleid ...

Determining Asynchrony in Node.js Through Programming

Is there a way to assess if a function can be executed asynchronously without requiring a callback? I am currently working with Node.js on the Intel Edison platform and utilizing mraa. The native C++ functions like i2c.readReg(address) do not have provisi ...

What is the best way to reset form after submission in Next.js?

I have a contact form and I want all the form values to be cleared after submitting the form. I've tried the following code, but the values of the form remain unchanged after submission. What could be causing this issue and how can it be resolved? ...

The drop-down menu fails to appear when I move my cursor over it

#menu { overflow: hidden; background: #202020; } #menu ul { margin: 0px 0px 0px 0px; padding: 0px 0px; list-style: none; line-height: normal; text-align: center; } #menu li { display: inline-block; } #menu a { display: block; position: relative; padding ...

JQuery does not operate on content that is fetched through ajax requests

I've been struggling with this issue for quite some time now and I just can't seem to figure out what I'm doing wrong. (I suspect it's related to the ajax response) I attempted to upload an image to the server using the uploadifive plu ...

When the screen is at mobile width, elements with the class "Responsive" are hidden using the display:none; property. These elements can be

Hey there! So, I've got this cool interactive banner on my website. It features 2 slider sections with some awesome products on the right side. The layout is responsive, meaning that when you switch to a mobile screen size (around 515px or less), the ...

Manipulating a dynamic array within an Angular repeater using the splice method

Encountering an issue with deleting an object from an array using splice. The array, dynamically created through a UI, is stored in $scope.productAttributes.Products. Here's an example of the array structure... [ { "ProductLabel":"Net", "Code ...

The autofocus feature does not function properly in an input tag that is not located within a form element

Is there a way to set the autofocus property in an input element that is not part of a form? I have tried adding the "autofocus" attribute to the input tag but it doesn't seem to be working. <div> //I have added the autofocus property her ...

Unable to subscribe due to the return value being an AnonymousSubject rather than an Observable

I am facing an issue in Angular 4 where I am attempting to retrieve details from a specific user when clicking on the 'user link profile'. However, I am unable to subscribe to my function because the return value of switchMap is AnonymousSubject ...

Next.js threw a wrench in my plans when the HTML syntax was completely disrupted upon saving the index.js

I have encountered an issue in my VSCode environment while working on a next.js project. Whenever I attempt to save the index.js file, the HTML syntax crashes. I am at a loss on how to resolve this issue, so any assistance would be greatly appreciated. Tha ...

run a function once ngFor has completed rendering the data

I'm attempting to run a function every time my ngFor finishes loading data from the API. However, the callback only works on the initial load of the ngFor. How can I make sure that the callback is executed whenever my ngFor data changes? I found a ...

transforming a multidimensional array to JSON format

Here is my complex array that I am struggling to encode into JSON format and get the expected result. array ( 1 => array ( 'text' => 'Dashboard', 'spriteCssClass' => 'rootfolder', 'exp ...

Utilizing Promise.all to update subdocuments with Mongoose

Encountered an error while checking the value in promiseArr, seeking assistance or suggestions for a better approach. Thanks! **Error** <rejected> { MongooseError: Callback must be a function, got [object Object] at new MongooseError (D:\P ...

Using PHP to handle empty values in a JSON database

I am completely new to php and I am trying to create a json service that will save registration form values in a database. The issue I am facing is that it is saving empty values into the database. I am struggling to understand how to extract the values fr ...