10
var img = new Image();
img.src = "images/myFolder/myImage.png";

The above will only load myImage.png. How to load all images of myFolder?

isherwood
  • 58,414
  • 16
  • 114
  • 157
MaiaVictor
  • 51,090
  • 44
  • 144
  • 286

4 Answers4

18

If your image names are sequential like your said, you can create a loop for the names, checking at every iteration if image exists - and if it doesn't - break the loop:

var bCheckEnabled = true;
var bFinishCheck = false;

var img;
var imgArray = new Array();
var i = 0;

var myInterval = setInterval(loadImage, 1);

function loadImage() {

    if (bFinishCheck) {
        clearInterval(myInterval);
        alert('Loaded ' + i + ' image(s)!)');
        return;
    }

    if (bCheckEnabled) {

        bCheckEnabled = false;

        img = new Image();
        img.onload = fExists;
        img.onerror = fDoesntExist;
        img.src = 'images/myFolder/' + i + '.png';

    }

}

function fExists() {
    imgArray.push(img);
    i++;
    bCheckEnabled = true;
}

function fDoesntExist() {
    bFinishCheck = true;
}
Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136
11

JavaScript can't directly access the contents of a file system. You'll have to pass the contents using a server-side script (written in PHP, etc) first.

Then once you have that, you can use a loop in your JavaScript to load them individually.

tskuzzy
  • 35,812
  • 14
  • 73
  • 140
1

You need some way to get the list of files in that folder. This can either be defined manually as an array, or retrieved by an AJAX request to a server-side script that lists the files for you. Either way, there no "magic" method to get all the images in a folder.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

If you have all the names of the files in the folder, you'll need to loop through and open each image by name. You can't just load the whole folder directly and you can't access the file system in Javascript to get the names, you'll need to pass them to the page via something like PHP.

peacemaker
  • 2,541
  • 3
  • 27
  • 48