What is the best way to showcase just 5 photos while also incorporating a "load more" function with

Is there a way to display only 5 images from a list on the first load, and then show all images when the user clicks on "load more"?

Here is the code I have:

 $('.photos-list').hide();
 $('.photos-list').slice(1, 5).show();
    
$('#loadAllImages').click(function(){
 $('.photos-list').show();
});
   .photos-list ul,
            .videos-list ul {
                margin: 0px;
                padding: 0px;
            }
            
            .photos-list ul li,
            .videos-list ul li {
                list-style: none;
                float: left;
                width: 18%;
                margin: 5px;
                position: relative;
            }
            
            .photos-list ul li img,
            .videos-list ul li img {
                width: 100%;
                border-radius: 10px;
                height: 110px;
            }
            
            .photos-list ul li span,
            .videos-list ul li span {
                position: absolute;
                bottom: 0;
                right: 0;
                background: rgba(0, 0, 0, .5);
                padding: 5px 10px;
                cursor: pointer;
            }
            
            .photos-list ul li span svg,
            .videos-list ul li span svg {
                color: #fff;
            }
            
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="photos-list">
<ul>
<li> <img src="https://picsum.photos/200"/></li>
<li> <img src="https://picsum.photos/200"/></li>
<li> <img src="https://picsum.photos/200"/></li>
<li> <img src="https://picsum.photos/200"/></li>
<li> <img src="https://picsum.photos/200"/></li>
<li> <img src="https://picsum.photos/200"/></li>
<li> <img src="https://picsum.photos/200"/></li>
<li> <img src="https://picsum.photos/200"/></li>
<li> <img src="https://picsum.photos/200"/></li>
<li> <img src="https://picsum.photos/200"/></li>
</ul>
<button type="button" id="loadAllImages">Load all Images</button>
</div>

Thank you for any assistance provided!

Answer №1

To simplify the process, you can add a hidden class to each element and then use a conditional statement to display only the elements with an index lower than 5. Additionally, you can set up an event listener to remove the hidden class from all elements when a specific button is clicked.

$(document).ready(function() {
  const maxDisplay = 5

  function showElement(element) {
    return element.removeClass('hidden')
  }

  $('li').each(function(index) {
    index < maxDisplay ?
      showElement($(this)) : null
  })

  $('#loadAllImages').click(function() {
    $('li').each(function() {
      showElement($(this))
    })
  })
});
.photos-list ul,
.videos-list ul {
  margin: 0px;
  padding: 0px;
}

.photos-list ul li,
.videos-list ul li {
  list-style: none;
  float: left;
  width: 18%;
  margin: 5px;
  position: relative;
}

.photos-list ul li img,
.videos-list ul li img {
  width: 100%;
  border-radius: 10px;
  height: 110px;
}

.photos-list ul li span,
.videos-list ul li span {
  position: absolute;
  bottom: 0;
  right: 0;
  background: rgba(0, 0, 0, .5);
  padding: 5px 10px;
  cursor: pointer;
}

.photos-list ul li span svg,
.videos-list ul li span svg {
  color: #fff;
}

.hidden {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="photos-list">
  <ul>
    <li class="hidden"> <img src="https://picsum.photos/200" /></li>
    <li class="hidden"> <img src="https://picsum.photos/200" /></li>
    <li class="hidden"> <img src="https://picsum.photos/200" /></li>
    <li class="hidden"> <img src="https://picsum.photos/200" /></li>
    <li class="hidden"> <img src="https://picsum.photos/200" /></li>
    <li class="hidden"> <img src="https://picsum.photos/200" /></li>
    <li class="hidden"> <img src="https://picsum.photos/200" /></li>
    <li class="hidden"> <img src="https://picsum.photos/200" /></li>
    <li class="hidden"> <img src="https://picsum.photos/200" /></li>
    <li class="hidden"> <img src="https://picsum.photos/200" /></li>
  </ul>
  <button type="button" id="loadAllImages">Load all Images</button>
</div>

Answer №2

Upon user request, the list will dynamically populate with images. In this demo, a single image is used repeatedly within an array.

let allImages = ['https://picsum.photos/300/100', 'https://picsum.photos/300/100', 'https://picsum.photos/300/100', 'https://picsum.photos/300/100', 'https://picsum.photos/300/100', 'https://picsum.photos/300/100', 'https://picsum.photos/300/100', 'https://picsum.photos/300/100', 'https://picsum.photos/300/100', 'https://picsum.photos/300/100']



function addImages(start, end) {

   let myList = document.getElementById('myList');   
      
   for (let i = start; i <= end; i++) {
   
     let image = document.createElement('img');
     image.src = allImages[i];
     let listItem = document.createElement('li').appendChild(image);
     
     myList.appendChild(listItem)
      
   }

}


addImages(0, 4);
<ul id="myList">

</ul>

<input type="button" value="More" onClick="addImages(5, 9)">

Answer №3

If you're looking for the most effective approach, follow these steps:

  1. Organize all images in a publicly accessible folder
  2. Create a JavaScript script that utilizes AJAX to send requests to the server
  3. Have the server respond with a JSON containing the URLs of the images
  4. Add a click event listener to the "Show More" button that dynamically creates image elements using JS

IMPORTANT: Ensure that the server response supports pagination for best practices.

Alternatively, if you want to test using only JS without a backend, consider utilizing @charlie's method, which covers Step 4 and is considered a Standard Method.

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

Choose a looping function in React JS that iterates over an array of objects

I have an array of objects let arr = [0: {received: "Return Received", approved: "Approved", rejected: "Rejected"} 1: {authorized: "Authorized", received: "Return Received"}} I am looking to populate a < ...

Methods for Hiding and Revealing a UIView with the Press of a Single UIBarButtonItem

In my iOS app, I have created a right bar button item programmatically and added it to my view controller. Additionally, I have also added a UIView to the view controller. The action for my bar button item has been set. Currently, the UIView is hidden when ...

Is there a way to associate a click event with an angular2 template interpolation?

Can a click event be bound to an interpolation? Whenever I try to run the code below, I encounter the following ERROR Error: Uncaught (in promise): Error: Template parse errors: Parser Error: Got interpolation ({{}}) where expression was expected at col ...

Utilizing the map() method for iterating through a nested property within a React component

Currently, my React setup involves rendering a prop named area which has the following structure: [{ "id": 1, "name": "Europe", "Countries": [{ "id": 1, "name": "Iceland", "Cities": [{ "id": 1, " ...

Redirect the Submit button to the specified URL from the form element

Looking for a way to create a form with two fields: Username and Password. Upon clicking submit, the username and password should be added to the URL in a specific format. For instance: The URL structure will remain the same, only the "username_entered_i ...

How can I change the transparency of a CSS background color using JavaScript?

I have a question about CSS: .class1 { background: #fff } Now, I need to achieve the following: .class2 { background: rgba(255,0,0,0.5) }; Is there a way to use JavaScript only to change the background property of .class1 and give it an opacity of 0.5? ...

Managing properties of classes within callbacks using TypeScript

I am currently working on the following task: class User { name: string; userService: UserService; //service responsible for fetching data from server successCallback(response: any) { this.name = string; } setUser() { ...

Creating a text design that spans two lines using Scalable Vector Graphics (SVG

I am working with an SVG that displays strings pulled from an Array... {"label":"Here is an example of the string...", "value":4}, The text above is shown in an SVG element as... <text>Here is an example of the string...<text> I would like ...

Solid white border encasing the full page

While I know there have been similar questions asked before, I believe mine is unique because I haven't found a solution anywhere. Recently, I started a new project in React. I decided to remove App.css and index.css, and created a single component wh ...

Encountering a 404 error in an AngularJS app within Cordova on Android

Currently, I am working on an android application using Cordova and AngularJS (front-end framework OnsenUI). Below is the code snippet for my GET request to retrieve data from the server: $http.get(url+"getlotterylist").then(function(msg){ $scope. ...

Having Trouble with Jquery Toggle Function!

I have put together a small Jquery script after much contemplation (since I am new to this), and unfortunately, it is not working as expected! Here's the issue: in my code, I want to click on an element defined by the variable trigger, and when clicke ...

Javascript cards arranged in descending order

I'm in the process of developing a sorting feature that arranges cards in the DOM from Z to A with the click of a button. Although I've successfully implemented the logic for sorting the array, I'm facing difficulties in rendering it. Withi ...

Tips for making sure AngularJS runs a function and its subfunction sequentially

How do I run the code below to display the details of each flavor and its corresponding ITEM ID in a specific order. Execution Format: Flavor1, Flavor2 -- Getflavors() Flavor1 ITEM1, ITEM2... -- GetItemIDs_ofeachFlavor(MapFlvID) GET ITEM1 DETAILS and ad ...

There was an issue with the v-on handler: "An error occurred because it was unable to read properties of an undefined value (specifically 'input')."

Can anyone help me? When I click the icon inside the avatar, I want to select a file. But I'm getting an error: Error in v-on handler: "TypeError: Cannot read properties of undefined (reading 'input'). Could anyone help me? <v-row v-for=" ...

Generate a new span element within a div element programmatically using Vuex

I have integrated an existing web application developed using vue.js. Below is the code snippet: function () { var e = this, t = e.$createElement, n = e._self._c || t; return e.messag ...

Nested Async await within a timer is failing to provide the expected result

Currently, I am working on testing the responses of endpoints using Mocha and Chai tests. Below you can find the code snippet for the same: async function fetchUserData (userId) { let response; let interval = setInterval(async () => { ...

Issue encountered in AngularJS while configuring resources for the action `query`: Anticipated response was an object, but received an array instead

I've been attempting to utilize Angular 1.3 to access a REST service, but I keep encountering an error stating "Error: error:badcfg Response does not match configured parameter". My suspicion lies in the controller where I invoke $scope.data. Even th ...

Enable the Chrome extension to interact with the RESTAPI

As I develop a Chrome extension and Rest API, my current focus is on their integration. However, I have some security concerns that need to be addressed. The purpose of the extension is to retrieve data from the API. This data is not personalized for any ...

Error in Vue Vuelidate appearing when form is submitted with empty data property

I have been working on some basic validation for required fields and minimum length. The problem arises when I submit a network request for data insertion, the validation works perfectly fine. However, after the network call, if I try to make my text fie ...

Error encountered while using Google Translate with XMLHttpRequest (Missing 'Access-Control-Allow-Origin' header)

Trying to access a page that utilizes Google Translate is resulting in the following error: XMLHttpRequest cannot load http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit. No 'Access-Control-Allow-Origin' heade ...