0

How can I store the contents of a folder which consist entirely of images. I can do it this way.

var files = ["1.jpg","2.jpg",
             "3.jpg","4.jpg","5.jpg","6.jpg",
             "7.jpg","8.jpg","9.jpg","10.jpg",];

but I'd like to do it more dynamically I'm planning on having 100's of images in the folder. I'm thinking something like this pseudo code

var images
 for i to number_of_items_in_folder
      images[i]= image_from_folder

The images are coming from a folder (local) called images

Wanting to learn
  • 468
  • 1
  • 7
  • 25
  • 5
    I think you're getting Javascript and Python mixed up.. – eatonphil Jun 20 '13 at 20:53
  • 2
    What folder? Where are these images coming from? What *exactly* are you trying to do? – gen_Eric Jun 20 '13 at 20:55
  • The question is too vague, explain what exactly you're trying to do. – Vitim.us Jun 20 '13 at 20:55
  • I assume you simply want to build an array of strings dynamically. JavaScript tutorials should cover arrays thoroughly. Have a look at http://eloquentjavascript.net/chapter4.html and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Predefined_Core_Objects#Array_Object. Also have a look at the `for` loop: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for. These are all basics IMO. – Felix Kling Jun 20 '13 at 20:55
  • you can use input[type=file] with a webkitdirectory attrib to load a folder in JS. You can then loop through the input's files[] collection and push a new filename into a collection array for each image file. – dandavis Jun 20 '13 at 20:57
  • 2
    People telling he is mixing things: Ever heard of pseudocode? I updated the question – mplungjan Jun 20 '13 at 20:59
  • It's still not clear where the code is running. If you run the code in the browser, then you cannot access the local file system. – Felix Kling Jun 20 '13 at 21:02
  • Assuming you are on node.js, perhaps this is useful for you: http://stackoverflow.com/questions/2727167/getting-all-filenames-in-a-directory-with-node-js – Juan Guerrero Jun 20 '13 at 21:03

1 Answers1

1

To do this on the client only you will need a trick or a hardcoded value

So

var images = []; 
// you tell the script how many and they all have numbers from 0 to here 87
for (var i=0; i<87; i++) {
  images.push(i+".jpg");
}

If you do NOT know how many you have, you need to preload them

var images = [],done=false,i=0; 
while (!done) {
  var image = new Image();
  image.onerror=function() {
    done=true;
  }
  image.onload=function() {
    images.push(this.src);
  }
  image.src=i+".jpg";
  i++;
}

and if they all have different names, then you need a server script that will build the array for you.

mplungjan
  • 169,008
  • 28
  • 173
  • 236