I am trying to load a series of images inside a div using for loop and when the file does not exist, the for loop breaks. This code doesn’t seem to work.
I’ve tested many others but no success. Any tips?
HTML:
<div id="project_img">
</div>
JavaScript:
function load_projects()
var project_array = new Array();
var project_name;
for(var i = 0; i < 7; i++) {
project_array.push(new Image());
project_name = "project_" + i;
project_array[i].src = "images/" + project_name + ".png";
project_array[i].id = project_name;
$("#project_img").append(project_array[i]);
$("#" + project_name).error(function() {
alert(i);
i = 7;
})
}
}
$(document).ready(function() {
load_projects();
});
The problem is, that the error-callbacks will be called after the
forloop has finished (runs from 0 till 7).If you want to start loading next image if there is no error loading the current image, you have to change your strategy: you need a success callback, which starts loading the next one. jQuerys load method can be used to set a callback if an image has been successfully loaded:
If current image has been loaded and not all images has been displayed, start loading next one:
So the
forloop isn’t needed anymore. The complete code is:Not neccessary but if you want you can add the error callback again:
Also see my jsfiddle. (There I have added one existing image.)