0

This is my js and jq code :

for (i = 0; i < data.length; i++) {
    var $nItem = $('.Search_result_template').clone().removeClass("Search_result_template");
    src = Link_DB + data[i]._id + "/" + ReadConfigurationSettings_img_Upload_Name()+"0";
    $("<img/>")
        .on('load', function () {
            alert("image loaded correctly");
            alert("src: " + src);
            $nItem.find('.var_link_img').attr('href', src);
        })
        .on('error', function () {
            alert("error loading image"); var src = ReadConfigurationSettings_Link_Default_img();
            $nItem.find('.var_link_img').attr('href', src);
        })
        .attr("src", src);
    $nItem.find('.var_link_img').text('Image');
    $nItem.attr("id", "Search_result_template_" + i);
    //alert($nItem.html());
    $Search_Result.append($nItem);
}

The loop is iterated before testing if the image loaded successfully or there is an error. Thus, if I have many elements the src isn't correctly associated to each image link.

How can I wait for:

$("<img/>").on('load', function () {});

to be executed so i can get the good src for $nItem.find('.var_link_img').attr('href', src);

The result of this code shows the first link(i==0) as null and the second one(i==1) with the src of the precedent.

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
Dev pro
  • 620
  • 1
  • 7
  • 12
  • 3
    possible duplicate of [JavaScript waiting until an image is fully loaded before continuing script](http://stackoverflow.com/questions/16919862/javascript-waiting-until-an-image-is-fully-loaded-before-continuing-script) – Marko Gresak Aug 19 '15 at 17:05
  • See http://stackoverflow.com/questions/29044852/preloading-images-in-html – guest271314 Aug 19 '15 at 17:09

0 Answers0