HTML OnMissingImage - With Dynamic Content
Posted By : todd sharp Posted At : April 21, 2008 12:41 PM Posted In: Ajax
0
This morning Rob Gonda blogged about using the 'onerror' attribute of the <img> tag to display an alternate image if your image does not load. I tried this solution within a dynamic Spry region, and it didn't seem to work. I'm guessing that the onerror is fired once and only once, and since the image src is dynamic (within my Spry region) it is not firing the onerror again so the initial replacement image is loaded.
Thanks to some good discussion in the comments I devised a method to get this to work with my Spry region. It's pretty simple really, just register an observer on the region, and once the region is updated loop over the dataset, checking to see if the image is loaded. If not, replace it with your 'oops' image. Here's some code:
if(type == 'onPostStateChange'){
var ds = dsName.getData();
for(var i = 0; i<ds.length; i++){
//assumes you've named your image {ID}_img
var id = ds[i].ID + '_img';
//check to see if the image was loaded
if(!document.images[id].complete){
document.getElementById(id).src = 'oops.jpg';
}
}
}
}
Spry.Data.Region.addObserver('regionName', observer);
That's it!


