0

I'm displaying a series of thumbnails to the user, using a for loop. If thumbnails[i].path fails to load, I'm wanting to load thumbnail_unavailable.jpg in its place.

As I understand, jQuery's .error() handeler should be used as follows.

for (var i=0; i<thumbnails.length; i++){
   var txt = "";
   txt += "<div class...>";

       // if no image, load "Screenshot Unavailable" thumbnail
       var temp_img = $('<img id="'+thumbnails[i].video_id+'" />');
       temp_img.error(function () {      
          // temp_img.attr doesn't work
          temp_img.attr('src','images/thumbnail_unavailable.jpg');
          // nor does: $('#'+thumbnails[i].video_id).attr('src','...jpg');
          // nor does: $(this).attr('src','...jpg');
       }).attr('src', thumbnails[i].path);

    txt += temp_img.get(0).outerHTML;                                
    txt += "</div>";

   $('#putVidThumbsHere').append(txt);
}

The thumbnails, however, retain their broken thumbnail[i].path regardless if I use $(this) $('#'... or temp_img

Kyle Cureau
  • 19,028
  • 23
  • 75
  • 104

1 Answers1

0

I tried everything, including on/one bindings to handle the failed resource. Somehow (and I'd love an explanation as to why), the references made in that for loop did not mix well with the delay time it required to make sure the URL to the image actually failed.

I finally found this brilliant solution on another SO thread:

function ImgError(source){
    source.src = "/images/noimage.gif";
    source.onerror = "";
    return true;
}

<img src="someimage.png" onerror="ImgError(this);"/>
Community
  • 1
  • 1
Kyle Cureau
  • 19,028
  • 23
  • 75
  • 104
  • You probably should have killed your own question in that case as a duplicate. – tomdemuyt Jun 25 '12 at 15:39
  • @tomdemuyt, have you read that thread? Same solution, different question (as is evidenced by the fact that the 2nd highest-voted response is a viable solution for that OP, but doesn't work for the code example in this thread). But on a more technical note: I wasn't even allowed to close this thread until the last two people withdrew their answers. – Kyle Cureau Jun 25 '12 at 19:31