Skip to content
Advertisement

How do I show png images based on their names in javascript?

I have a folder with png images and several other types of files. I only want to display the png images in the order of their names, how can I do that? All images end in a number; for example, each image is titled “image_001”, “image_002”, and so on. Right now I have all the images grouped together in a class as shown below but I’d prefer not to have to add every individual image if I didn’t want to include any other file types. Thank you in advance.

 <section>
        <img class="pics" src="imgfolder/picture_001.png" style="width:80%">
        <img class="pics" src="imgfolder/picture_002.png" style="width:80%">
        <img class="pics" src="imgfolder/picture_003.png" style="width:80%">
 </section>

<script type="text/javascript">
        var index = 0;
        change();

        function change() {
             var images = document.getElementsByClassName('pics');

             for(var i = 0; i < images.length; i++) { 
                 images[i].style.display = "none"; 
             }       
             index++;

             if(index > images.length) { 
                 index = 1; 
             }

             images[index - 1].style.display = "block";

             setTimeout(change, 3000);
         }
</script>

Advertisement

Answer

The JS code is commented with what it does. I’ve tested this with the same file structure that you used in your question, but you can change it on JS line 9.

<section id="img-container"></section>
const numOfPictures = 3; // The number of pictures in folder
const picturesNumberLength = 3; // "000"
let imageIndex = 1;
let imagesArray = [];
const imagesContainer = document.getElementById("img-container"); // Get the images container, has id "img-container"

for (let i = 1; i < numOfPictures + 1; i++) { // Starts at a 1 index "001"
  const img = document.createElement("img"); // Create an image element
  img.src = `imgfolder/picture_${(i+"").padStart(picturesNumberLength,"0")}.png`; // Set the source to "imgfolder/picture_001" or other number, works up to 999
  img.classList.add("pics"); // Add the pics class
  img.style.width = "80%"; // Sets width to 80%
  img.style.display = "none"; // Turns off displaying it
  imagesContainer.appendChild(img); // Puts the image in the image container
  imagesArray.push(img); // Push the reference to the array
}
imagesArray[0].style.display = "block"; // Display the first block
setInterval(() => { // Every 3000ms (3secs), do this
  imagesArray[imageIndex].style.display = "block"; // Turn displaying on
  if (imageIndex > 0) imagesArray[imageIndex-1].style.display = "none"; // Turn the previous one off
  else imagesArray[numOfPictures-1].style.display = "none";
  imageIndex++; // Change the index
  if (imageIndex >= numOfPictures) imageIndex = 0; // Go back to the beginning after going to the end
}, 3000);
Advertisement