jamo
jamo

Reputation: 1

Displaying multiple images in html from folder

Hi I'm new to html and I was just making something for fun as a practice. I'm trying to display multiple images in html, and I wasn't sure how. For example,

  <img src="/images/1/1.jpg" class="center">
  <img src="/images/1/2.jpg" class="center">
  <img src="/images/1/3.jpg" class="center">
  <img src="/images/1/4.jpg" class="center">

I have this right now, but I don't want to write this every time. I was wondering how I would do it. Could I use JavaScript or php or anything to put all images in the folder at once?

Upvotes: 0

Views: 1831

Answers (2)

Mister Jojo
Mister Jojo

Reputation: 22320

simple code on PHP:

<?php
  $refFolder = "/images/1/";
  function folderList($Path) {
    return  array_slice(scandir($Path,SCANDIR_SORT_ASCENDING), 0); 
  }
  foreach(folderList($refFolder) as $file) { 
    $Z_info = pathinfo($file, PATHINFO_FILENAME);
    $Z_type = pathinfo($file, PATHINFO_EXTENSION);
    if ($Z_type == 'jpg') { 
?>
    <img class="center" 
      src="<? echo $refFolder.$file; ?>" 
      alt="<? echo $Z_info; ?>" 
    />
<?php } } ?>

Upvotes: 1

Ajay Ullal
Ajay Ullal

Reputation: 378

You need to create a rest endpoint which returns you the list of all the images in your folder and then you could loop through the array and add your images to the DOM dynamically.

Ex:

const folder = '/folder';
const arr = ['img1.jpg', 'img2.jpg'];

arr.forEach(image => {
   const imgCntr = document.getElementById('imgCntr'); // Div which contains the iamges
   const img = document.createElement("IMG");
   img.src = `${folder}/${image}`;
   imgCntr.appendChild(img)
});

Upvotes: 0

Related Questions