Search code examples
javascriptjqueryonerror

Where to swap image if broken


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?


Solution

  • Figured out the easiest wasy to do it is inline:

    html += '<img src....onerror="this.onerror=null;this.src=\''+image.preview2+'\';">';