-1

I use lots of images on a page which are loaded into DOM eg

html += '<img src="'+image.preview+'" title="View larger image" alt="'+image.item_title+'" height="'+image.display_height+'" width="'+image.display_width+'">';

The data comes from an ajax call and is in a FOR loop, one for each image. I have two images refs in case one is broken image.preview and image.preview2 (I use two as image.preview is local but in case of error then image.preview2 is original image)

If image.preview is broken I want to switch to image.preview2

I'm trying the following but not sure where to place it?

$('img').on('error', function() { this.src = image.preview2; });

I've tried before the html +=, after, in the middle of but nothing seems to work - any ideas?

StudioTime
  • 22,603
  • 38
  • 120
  • 207

4 Answers4

1

If the preview2 image source is for every image different, then I suggest doing it within the for loop like this:

for(n in images) {
    var image = images[n];

    // create jQuery object (is not in the DOM jet)
    $img = $('<img title="View larger image" alt="' + image.item_title + '" height="' + image.display_height + '" width="' + image.display_width + '">');

    // is there an preview src?
    if(typeof image.preview == 'Undefined' || image.preview == '') { //nopes
        $img.attr('src', image.preview2);
    } else { //yes
        $img.attr('src', image.preview);
    }

    // add the image to the DOM
    $('#id_of_element').append($img);
}
Sven van Zoelen
  • 6,989
  • 5
  • 37
  • 48
0

you can do:

var newImg = $('<img src="'+image.preview+'" title="View larger image" alt="'+image.item_title+'" height="'+image.display_height+'" width="'+image.display_width+'">');
newImg.on('error', function() { this.src = image.preview2; }); 

and then

<the html container>.append(newImg);

this will make sure your image has all settings before it is added to the dom and fetched.

TheZuck
  • 3,513
  • 2
  • 29
  • 36
0

example:

function setDefaultImage(img)
{
  img.src = "images/candidates/human.jpg";
}

hope this will help you..

in your scenario..

html += '<img src="'+image.preview+'" title="View larger image" alt="'+image.item_title+'" height="'+image.display_height+'" width="'+image.display_width+'" onerror="'setDefaultImage(this)'">';

 function setDefaultImage(img)
    {
      img.src = "image.preview2";
    }
sasi
  • 4,192
  • 4
  • 28
  • 47
-2

Figured out the easiest wasy to do it is inline:

html += '<img src....onerror="this.onerror=null;this.src=\''+image.preview2+'\';">';
StudioTime
  • 22,603
  • 38
  • 120
  • 207