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
I tried everything, including
on/onebindings 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: