-1

I'm trying to create a lightbox for my site, and I want it to load all the images from a given directory with a filename like image#.jpg.

This is the code I have:

for(var i=0; i<1000; i++)
{
var filename = "images/image"+i+".jpg";
$.get(filename)
    .done(function() { 
            $('#lightbox').append('<a href="images/image'+i+'.jpg" data-lightbox="lb" data-title=""><img src="placeholder.gif"></a>');
        })
    .fail(function() {
        i=1000; //ugh
    });
}

It kind of works, but only tries to load image1000.jpg.

Also, is there a better way to do something like this? I'm sure saying 'do this a ton of times and stop when I manually change the for loop counter' is frowned on.

zzxjoanw
  • 374
  • 4
  • 16
  • 1
    possible duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Musa Apr 13 '14 at 17:36

1 Answers1

0

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;
}
Umair Rana
  • 683
  • 1
  • 6
  • 13