javascriptimageloopsgalleryportfolio

Adding images from a folder to website dynamically


I have a site which will have a gallery with 3 sections. Each section has up to 30 images. I will store the images in folders relating to the relevant sections (ie "img/gallery/category1", "img/gallery/category2" and "img/gallery/category3")

Basically instead of writing html to display each individual image, I would like to have a javascript loop which will look in the folder and display each image, and place the url within a predefined snippet of code, ie:

<div class="span4">
  <img src="img/gallery/category1/IMAGE-FILENAME1">
</div>

<div class="span4">
  <img src="img/gallery/category1/IMAGE-FILENAME2">
</div>

... etc, until all images from the folder have been processed... (also, I know I could be a bit smarter with the html above, but I want to communicate that I want each found image url to sit amongst a repeated snippet of code).

I'm still training in javascript, so I wondered whether there was a way I could do this?

Thanks


Solution

  • I found an alternative solution.

    I wasn't quite ready to tackle AJAX, JSON or anything listed below just yet. So I decided to look into using PHP. Solution as folows:

    I first of all used the following to go to and read the contents of the folder to an array:

    $directory = "DIRECTORY"
    
    $dirhandler = opendir($directory);
    
    $nofiles=0;
    while ($file = readdir($dirhandler)) {
    
    if ($file != '.' && $file != '..')
    {
      $nofiles++;
      $files[$nofiles]=$file;                
    }}
    

    And then using a foreach loop I iterated through the array, everytime echoing the html output which referenced the filename found.

    Works perfectly.