load all the pictures (jpg and png) automatically from a folder alphabeticaly

426 Views Asked by At

I am loading pictures from a photos folder manually like this :

<div class="container">

 <div class="item">
    <a href="#">
        <img type=file src="photos/01.jpg" />
    </a>
 </div>

 <div class="item">
    <a href="#">
        <img type=file src="photos/04.jpg" />
    </a>
 </div> 

How can i load all the pictures (jpg and png) automatically from this folder alphabeticaly ?

The pictures have random names, and are sometimes jpg or png.

The idea is to be able to load all the pictures from the folder, without specifying the number of pictures in the folder. for exemple if there is 2 pictures, it loads 2 pictures. 3 pictures in the folder, it load 3 pictures...

exemple of picture names to display: rrededd01.jpg, treddeeda.png, zsa99889.jpg

Thank you for your help.

2

There are 2 best solutions below

2
On

Assuming the HTML is being generated by a sever side language (PHP, Python, Ruby, C#, Java...) the usual approach would be to glob the directories containing the images, loop over the fs entries and generate an IMG tag for each.

9
On

Supposing that you are not dealing with a server-side language, the common approach would be using Javascript to dinamically append the images. You could try this code, replacing the part you provided; it will generate 4 images. You can just change the number 4 if you have more images.

<div class="container"></div>

<script>

// Change this if you have more or less than 4 images!
const quantityOfImages = 4;

// Declares an empty string which will save all the images HTML
let images = '';

// Loops to generate the HTML for each image
for(let i = 1; i <= quantityOfImages; i++) {
  // Assigns number; this is to get the number correctly formatted from 01 to 99
  const number = ('0'+i).substr(-2);

  images += `
    <div class="item">
        <a href="#">
            <img type=file src="photos/${number}.jpg" />
        </a>
    </div>
  `;
}

// Now .container has all the images!
document.querySelector('.container').innerHTML = images;

</script>