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

Creating a tooltip for new list items: A step-by-step guide

I'm currently working on creating a tooltip using JQuery for incoming list items. Users will input text in a textfield, press enter, and those values will be displayed in a visible list on the website. I intend to have a tooltip associated with each i ...

What sets $(document).on apart from ($ document).on in CoffeeScript?

One of my buddies is incorporating ($ document).on into his CoffeeScript script. I'm curious to know if this differs from the typical $(document).on and, if it does, how so? ...

The retrieval of JSON file using $.GetJson() is unsuccessful from local directory

There is a basic autocomplete program in place. The data entered in the textbox is successfully captured while debugging, however, the GetJson() function fails to retrieve the JSON file, causing the program to malfunction. Here's the relevant code sn ...

React Material-UI TextField with Throttling

After exploring React Material UI, I am interested in implementing a TextField component that offers both debouncing and controlled functionality. When we refer to "controlled," we mean that the value persistence is managed externally, with the component a ...

How to integrate VLC media player into an HTML webpage

I'm currently struggling to incorporate a VLC player into a website. What is the most effective method to achieve this task? I need to stream a video file using VLC and display it on the webpage for other users who are logged into my site to view. I&a ...

Issue with HTML While Utilizing wp_get_attachment_image

This script : $source = wp_get_attachment_image( get_the_ID(), 'medium' ); $weburl = wp_get_attachment_image_url( get_the_ID(), 'full' ); echo( '<p><a href="%s"><img src="%s"></a></p>', $weburl, ...

The compatibility issue between Vue 2.6.12 and Laravel is causing difficulties for FullCalendar to function properly

Recently, I attempted to integrate the fullcalendar library version 5.9.0 into my project following the instructions provided in the documentation. <script> import '@fullcalendar/core/vdom' // resolves Vite issue import FullCalendar from ...

Buttons are misaligned and do not align on a straight line

Below is the code output: https://i.stack.imgur.com/avhUu.png I am attempting to enhance the symmetry of these buttons. The minus (-) button appears slightly smaller than the plus (+) button even though they have the same padding. I have experimented w ...

Running a Vue.js application on a hosting platform

I am currently facing an issue with my Vue.js application. I have set up a domain and subdomain for the application and now I want to host it. However, when I try to add the subdomain name, I keep encountering 500 Internal server errors. This is my first t ...

Create custom AngularJS directives for validation and store them in a variable

Through the use of AngularJS, I've developed a directive called "integer" that invalidates a form if anything other than integers are entered. Because I'm generating the page dynamically by fetching data from the database, it would be helpful to ...

Ensure the header remains fixed when scrolling in an HTML page with Bootstrap

I created the following code. However, when I scroll down the table, the header disappears from view. I would like the header to always remain at the top, even when scrolling. Despite searching Google multiple times and trying various solutions, I have no ...

Utilizing background styles for enhancing the appearance of Ionic side menus

I've been experimenting with ionic and angular.js, trying to figure out the best way to apply background styles to side menus. I currently have a blurred background image with content boxes placed on top of it. My goal is to keep the background fixed ...

Displaying the number of tasks completed compared to the total number of tasks within a JavaScript ToDo list

Currently, I'm in the process of creating a basic ToDo list using HTML, JS, and CSS. The last task on my list is to display to the user the total number of tasks and how many have been completed. For instance, if there are 3 completed tasks out of 7 i ...

Navigation bar's active area does not span the full height

I'm facing some issues with the navigation bar on my responsive website. One issue is that the clickable area for the links does not extend to the full height of the nav bar, and I would like it to cover the entire height. Another problem arises whe ...

how to use AngularJS filter and ng-options to format specific options as bold in a select dropdown

I am currently utilizing AngularJS ng-options to populate specific select elements. I am interested in bolding and disabling certain options. Despite trying to achieve this using the filter along with ng-options, I have been unsuccessful so far. While I ca ...

What is the optimal location for making API requests in a React/Redux/Reach Router application?

I'm struggling to figure out the optimal location for making API calls in my app. My main component structure looks like this: ReactDOM.render( <React.StrictMode> <Provider store={store}> <Router /> ...

What could be causing the erratic jumping behavior of the "newsletter sign-up" form within my modal dialog window?

On the homepage, there is a modal window that appears upon every pageload (it will be changed later), however, there seems to be an issue with the 'email sign up' form inside the window. The form seems to momentarily display at the top of the si ...

Calculating the total sum of values in a table using Jquery

Can anyone help me calculate the sum of input values from a table using HTML and jQuery? Here is my current code: HTML: <tr id='saved1'> <td><input class='qty'/></td> <td><input class='price&apo ...

When using NVDA, the close button is being read multiple times, whereas in JAWS it is being read correctly

Here is the code for a close button within a modal pop-up: <h2 class="sc-ejdXBC byjYiM MuiTypography-root MuiTypography-h6 sc-EoWXQ kOYWJk MuiDialogTitle-root" id="popupTitle"> Default Pop-UP Title <button class="sc-dm ...

"Experience the power of Angular.js through seamless animations created by blending the capabilities

I want to smoothly fade out the old view and fade in the new view. The challenge is that the new content must be positioned absolutely until the old one fades out. I also want to set a specific top position and height for the new content, but when I try to ...