jquery - Is there a way to programmatically determine that an image link is bad? -
in site i'm working on, image displayed not (displayed) because link bad or stale (or whatever). can see here: why dynamic html seemingly randomly placed?
when happens, want able show "image unavailable" message image be. possible? if so, 2 things needed:
1) able determine programmatically image not being displayed 2) replace it, in case, aforementioned message
perhaps (pseudocode):
if (imagemissing) { $('img').attr('src', 'imagemissing.png'); }
?
update
okay, code should like:
function dosomething() { var htmlbuilder = ''; $.getjson('duckbills.json', function() { // each ... // process json file, building dynamic html htmlbuilder += 'img="bla.png"...'; $('img').error(function() { $(this).attr("src", "imagemissing.png"); }); }): }):
???
does cause each image, it's added, have error handler attached it, there n event handlers bound, 1 each image?
or should be:
function dosomething() { var htmlbuilder = ''; $.getjson('duckbills.json', function() { // each ... // process json file, building dynamic html htmlbuilder += 'img="bla.png"...'; }): $('img').error(function() { $(this).attr("src", "imagemissing.png"); }); }):
???
update 2
this code, , 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 don't know why...
sure is, error() method :
$('img').error(function() { $(this).attr("src", "imagemissing.png"); });
the error event sent elements, such images, referenced document , loaded browser. called if element not loaded correctly.
Comments
Post a Comment