In the site that I'm working on, the image displayed is not always (displayed) because the link could be bad or stale (or whatever). You can see it here: Why is my dynamic HTML seemingly randomly placed?
When that happens, I want to be able to show an "Image Unavailable" message where the image would be. Is that possible? If so, two things are needed:
1) To be able to determine programmatically that the image is not being displayed
2) To replace it, in that case, with aforementioned message
Perhaps something like (pseudocode):
if (ImageMissing) {
$('img').Attr('src', 'imageMissing.png');
}
?
UPDATE
Okay, so the code should be like:
function doSomething() {
var htmlBuilder = '';
$.getJSON('duckbills.json', function() {
// each ...
// process the json file, building dynamic html
htmlBuilder += 'img="bla.png"...';
$('img').error(function() {
$(this).attr("src", "imageMissing.png");
});
}):
}):
???
Does this cause each image, as it's added, to have that error handler attached to it, so that there are N event handlers bound, one for each image?
Or should it be:
function doSomething() {
var htmlBuilder = '';
$.getJSON('duckbills.json', function() {
// each ...
// process the json file, building dynamic html
htmlBuilder += 'img="bla.png"...';
}):
$('img').error(function() {
$(this).attr("src", "imageMissing.png");
});
}):
???
UPDATE 2
This is my code, and it doesn't work:
$.getJSON('Content/NBCCJr.json', function (data) {
$.each(data, function (i, dataPoint) {
if (IsYear(dataPoint.category)) {
htmlBuilder += '<div class=\"yearBanner\">' + dataPoint.category + '</div>';
} else {
htmlBuilder += '<section class=\"wrapper\" ><a id=\"mainImage\" class=\"floatLeft\" href=\"' +
dataPoint.imghref + '\"' + ' target=\"_blank\"><img height=\"160\" width=\"107\" src=\"' +
dataPoint.imgsrc + '\"' +
dataPoint.imgalt + '></img></a>' +
'<div id=\"prizeCategory\" class=\"category\">' +
dataPoint.category +
'</div><br/><cite id=\"prizeTitle\" >' +
dataPoint.title +
'</cite><br/><div id=\"prizeArtist\" class=\"author\">' +
dataPoint.author +
'</div><br/>';
if (dataPoint.kindle.trim().length > 2) {
htmlBuilder += '<button><a href=\"' + Urlize(dataPoint.kindle) + '\"' +
' target=\"_blank\">Kindle</a></button>';
}
if (dataPoint.hardbound.trim().length > 2) {
htmlBuilder += '<button><a href=\"' + Urlize(dataPoint.hardbound) + '\"' +
' target=\"_blank\">Hardbound</a></button>';
}
if (dataPoint.paperback.trim().length > 2) {
htmlBuilder += '<button><a href=\"' + Urlize(dataPoint.paperback) + '\"' +
' target=\"_blank\">Paperback</a></button>';
}
htmlBuilder += '</section>';
// Doesn't work
$('img').error(function () {
$(this).attr("src", "Content/NoImageAvailable.png");
});
}
}); //each
...and I don't know why...