javascript - Why does my img error function fail? -


some of img elements dynamically building may (do) fail. cases, have code got here:is there way programmatically determine image link bad? namely this:

    function getnatlbookcritics() {         var htmlbuilder = '';          // doesn't diddly-squat - wrong spot it?         $('img').error(function () {             $(this).attr("src", "content/noimageavailable.png");         });          $.getjson('content/nbccjr.json', function (data) {             $.each(data, function (i, datapoint) {     . . . 

...but it's not working. warum nicht?

update

with code inside .each portion of $.getjson() call:

var jobject = $('<img src=\"' + datapoint.imghref + '\"/>'); $(jobject).error(function () {     $(this).attr("src", "content/noimageavailable.jpg"); }); 

...all of images fail. datapoint.imghref contains such values as:

http://www.amazon.com/exec/obidos/asin/b00655kloy/garrphotgall-20 

update 2

in nuts hell, i'm adding "img src" so:

function getnatlbookcritics() {     var htmlbuilder = '';     $.getjson('content/nbcc.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>' +     . . .                 htmlbuilder += '</section>';             }     // had img err code         }); //each         $('#bookscontent').append(htmlbuilder);     });     //getnatlbookcritics 

...so can see img getting added dom; maybe fact i've got height , width properties img problem...

update 3

manmohan vyas: mean so:

}); //each         $('#bookscontent').append(htmlbuilder).     find("img").error(function(){          $(this).attr("src", "content/noimageavailable.png");     });     });     //getjson() 

?

update 4

this:

var jobject = $(htmlbuilder); jobject.find("img").error(function () {     $(this).attr("src", "content/noimageavailable.png"); }); $('#bookscontent').append(jobject); 

...didn't work.

and fwiw, changing this:

$('#bookscontent').html(''); 

. . . $('#bookscontent').append(htmlbuilder);

...to this:

$('#bookscontent').replacewith(htmlbuilder);

...didn't work (the right stuff populated, formatting got messed (instead of solid black background, each section had black background, overall background silver).

update 5

i thought of may causing problem: images i'm attempting show jpgs, "image not available" image png. make difference? possibly causing rendering engine confused? if so, i'll save fallback img jpg...

update 6

nope, these last 2 attempts didn't work either. tried joseph myers idea, prestauls, changed this:

datapoint.imghref + '\"' + ' onerror=\"imgerror(this);\" target=\"_blank\"><img height=\"160\" width=\"107\" src=\"' + datapoint.imgsrc + '\"' + 

..to this:

datapoint.imgsrc + '\" onerror=\"imgerror(this);\"' + datapoint.imgalt + '></img></a>' + 

...and no difference. asked on jquery forum bit ago: i'm grasping @ straws here, wonder if having mismatched jquery/jqueryui versions problem? in order support older browsers, i'm still using jquery 1.9.1, on "bleeding edge" regards jqueryui version 1.10.3.

update 7

okay, here's all pertinent code (some redundant , moot code refactored out has been elided comply so's length limits). (static) css shouldn't matter, right? other "code" web.config , things of nature, none of should having effect on why can't fallback images display.

a lot of failed attempts noimageavailable.png display commented out.

@{     layout = "~/_sitelayout.cshtml";     page.title = "my next winner"; } <div id="tabs" class="content-wrapper">     <ul>         <li><a href="#tab-books">books</a></li>         <li><a href="#tab-movies">movies</a></li>         <li><a href="#tab-music">music</a></li>     </ul>     <div id="tab-books">         <select id="bookdropdown">             <option value="pulitzer">pulitzer</option>             <option value="nbcc">national book critics circle</option>             <option value="nba">national book awards</option>             <option value="noba">national outdoors book awards</option>         </select>         <div id="bookscontent" class="clearfix">content in books tab</div>     </div>     <div id="tab-movies"> 

. . . . . .

<script>     $.ajaxsetup({ cache: false });     var currentbookselection = '';      var currentmovieselection = '';     var currentmusicselection = '';      function imgerror(image) {         image.onerror = "";         image.src = "content/noimageavailable.png";          return true;     }      // books // todo: refactor: have 1 "getbooks()" function, passing in name of json file     function getnatlbookcritics() {         var htmlbuilder = '';          $.getjson('content/nbcc.json', function (data) {             $.each(data, function (i, datapoint) {                 if (isyear(datapoint.category)) {                     htmlbuilder += '<div class=\"yearbanner\">' + datapoint.category + '</div>';                 } else { // see snippet @ top of unit dealing landscape-oriented books (such children's books) change height , width of img                     htmlbuilder += '<section class=\"wrapper\" ><a id=\"mainimage\" class=\"floatleft\" href=\"' +                         datapoint.imghref + '\"' + ' target=\"_blank\"><img height=\"160\" width=\"107\" src=\"' +                         //datapoint.imghref + '\"' + ' onerror=\"imgerror(this);\" target=\"_blank\"><img height=\"160\" width=\"107\" src=\"' +                         //datapoint.imgsrc + '\" onerror=\"imgerror(this);\"' +                         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=\"' + urlify(datapoint.kindle) + '\"' +                             ' target=\"_blank\">kindle</a></button>';                     }                     if (datapoint.paperback.trim().length > 2) {                         htmlbuilder += '<button><a href=\"' + urlify(datapoint.paperback) + '\"' +                             ' target=\"_blank\">paperback</a></button>';                     }                     if (datapoint.hardbound.trim().length > 2) {                         htmlbuilder += '<button><a href=\"' + urlify(datapoint.hardbound) + '\"' +                             ' target=\"_blank\">hardcover</a></button>';                     }                     htmlbuilder += '</section>';                      //// doesn't work                     //$('img').error(function () {                     //    $(this).attr("src", "content/noimageavailable.png");                     //});                     // when answer, try this: <-- fail                     //var jobject = $('<img src=\"' + datapoint.imghref + '\"/>');                     //var jobject = $('<img src=' + datapoint.imghref + ' />');                     //$(jobject).error(function () {                     //    $(this).attr("src", "content/noimageavailable.jpg");                     //});                 }             }); //each             //var jobject = $(htmlbuilder).find('img').error(function () {             //    $(this).attr("src", "content/noimageavailable.png")             //});              //$("#bookscontent").html(jobject);             //var jobject = $(htmlbuilder);             //jobject.find("img").error(function () {             //    $(this).attr("src", "content/noimageavailable.png");             //});             //$('#bookscontent').append(jobject);              // 7/23             //imageerror = function (it) {             //    $(it).attr("src", "content/noimageavailable.png");             //};             //htmlbuilder = htmlbuilder.replace(/<img/g, '<img onerror="imageerror(this)"');             //var jobject = $(htmlbuilder);              //$("#bookscontent").html(jobject);             // </ 7/23              //$('#bookscontent').html('');             //$('#bookscontent').append(htmlbuilder);              ////try 7/24/2013             //var $jobject = $('<img>');             //$jobject.error(function () { //$jobject jquery object, don't wrap again             //    $(this).attr("src", "content/noimageavailable.jpg");             //}).attr('src', datapoint.imghref);             //</try 7/24/2013              //$('#bookscontent').html(htmlbuilder);             $('#bookscontent').html(htmlbuilder).                  find('img, button').click(function (evt) {                      $(this).css('border', '1px solid red')                      //evt.preventdefault();                      //find('img').error(function() {                      //    this.src = "/content/noimageavailable.png"                      //})                  });              //$('#bookscontent').replacewith(htmlbuilder);                 //.find('img').error(function() {                 //    this.src = "content/noimageavailable.png"                 //    //this.src = "http://www.gravatar.com/avatar/317f4b62da2b0186feac9b6209793505?s=80&d=http%3a%2f%2fimg.zohostatic.com%2fdiscussions%2fv1%2fimages%2fdefaultphoto.png";                 //});             $('#bookscontent').css('background-color', 'black');             $('button').button();         }); //getjsonnbcc         $largest = 0;         $(".wrapper").each(function () {             if ($(this).height() > $largest) {                 $largest = $(this).height();             }         });         $(".wrapper").css("height", $largest);     }   // getnatlbookcritics()      function getpulitzers() {         // since pulitzers 1 shows when site first opens, added rel="nofollow"         // in each href; in way method differs other "getx" book methods         var htmlbuilder = '';          $.getjson('content/pulitzers2.json', function (data) {             $.each(data, function (i, datapoint) {                 if (isyear(datapoint.category)) {                     htmlbuilder += '<div class=\"yearbanner\">' + datapoint.category + '</div>';                 } else { // see snippet @ top of unit dealing landscape-oriented books (such children's books) change height , width of img                     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=\"' + urlify(datapoint.kindle) + '\"' +                             ' target=\"_blank\" rel=\"nofollow\" >kindle</a></button>';                     }                     if (datapoint.hardbound.trim().length > 2) {                         htmlbuilder += '<button><a href=\"' + urlify(datapoint.hardbound) + '\"' +                             ' target=\"_blank\" rel=\"nofollow\" >hardcover</a></button>';                     }                     if (datapoint.paperback.trim().length > 2) {                         htmlbuilder += '<button><a href=\"' + urlify(datapoint.paperback) + '\"' +                             ' target=\"_blank\" rel=\"nofollow\" >paperback</a></button>';                     }                     htmlbuilder += '</section>';                 }             }); //each             $('#bookscontent').html(htmlbuilder).      find('img, button').click(function (evt) {          $(this).css('border', '1px solid red')      });              $('#bookscontent').css('background-color', 'black');             $('button').button();         }); //getpulitzers         $largest = 0;         $(".wrapper").each(function () {             if ($(this).height() > $largest) {                 $largest = $(this).height();             }         });         $(".wrapper").css("height", $largest);         // not working; axed question on jquery forum         $('img, button').click(function (evt) {             $(this).css('border', '5px solid green');             evt.preventdefault();         });         // added 7/24/2013 - nothing         //$(function () {         //    $('a').click(function () {         //        open(this.href, 'newwin', 'toolbar=yes');         //        self.focus();         //        return false;         //    });         //});     } // getpulitzers()      function getnatlbook() { 

. . . } // getnatlbook()

    function getnoba() {         // load bookcontents using getjson     }      // movies     // movies differ books , music in of awards not have person winner - movie     // have check , conditionally add bit of html (what corresponds author in books ,     // artist in music)     function getmovies(pathtojsonfile) {         var htmlbuilder = '';          $.getjson(pathtojsonfile, function (data) {             // tried renaming above nbcc.json, won't work name...?!? $.getjson('content/nbcc.json', function (data) {             $.each(data, function (i, datapoint) {                 if (isyear(datapoint.category)) {                     htmlbuilder += '<div class=\"yearbanner\">' + datapoint.category + '</div>';                 } else { // see snippet @ top of unit dealing landscape-oriented books (such children's books) change height , width of img                     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.film +                         '</cite><br/>';                     if (datapoint.person.trim().length > 2) {                         htmlbuilder += '<div id=\"prizeartist\" class=\"person\">' + datapoint.person + '</div><br/>';                     }                     if (datapoint.bluray.trim().length > 2) {                         htmlbuilder += '<button><a href=\"' + urlify(datapoint.bluray) + '\"' +                             ' target=\"_blank\" >bluray</a></button>';                     }                     if (datapoint.dvd.trim().length > 2) {                         htmlbuilder += '<button><a href=\"' + urlify(datapoint.dvd) + '\"' +                             ' target=\"_blank\" >dvd</a></button>';                     }                     htmlbuilder += '</section>';                 }             }); //each             $('#moviescontent').html(htmlbuilder).                  find('img, button').click(function (evt) {                      $(this).css('border', '1px solid silver')                  });             $('#moviescontent').css('background-color', 'black');             $('button').button();             //console.log(htmlbuilder); <-- may want response click on tab when movie tab selected         }); //getoscars         $largest = 0;         $(".wrapper").each(function () {             if ($(this).height() > $largest) {                 $largest = $(this).height();             }         });         $(".wrapper").css("height", $largest);     }      // music      // "work" used "album or song or recording or performance" //todo: make generic "music" function la movies above     function getgrammies() {         var htmlbuilder = '';          $.getjson('content/grammies.json', function (data) {             $.each(data, function (i, datapoint) {                 if (isyear(datapoint.category)) {                     htmlbuilder += '<div class=\"yearbanner\">' + datapoint.category + '</div>';                 } else { // see snippet @ top of unit dealing landscape-oriented books (such children's books) change height , width of img                     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.work +                         '</cite><br/><div id=\"prizeartist\" class=\"work\">' +                         datapoint.artist +                         '</div><br/>';                     if (datapoint.mp3.trim().length > 2) {                         htmlbuilder += '<button><a href=\"' + urlify(datapoint.mp3) + '\"' +                             ' target=\"_blank\">mp3</a></button>';                     }                     if (datapoint.dvd.trim().length > 2) {                         htmlbuilder += '<button><a href=\"' + urlify(datapoint.dvd) + '\"' +                             ' target=\"_blank\">dvd</a></button>';                     }                     if (datapoint.vinyl.trim().length > 2) {                         htmlbuilder += '<button><a href=\"' + urlify(datapoint.vinyl) + '\"' +                             ' target=\"_blank\">vinyl</a></button>';                     }                     htmlbuilder += '</section>';                      //// doesn't work                     //$('img').error(function () {                     //    $(this).attr("src", "content/noimageavailable.png");                     //});                 }             }); //each             $('#musiccontent').html(htmlbuilder).      find('img, button').click(function (evt) {          $(this).css('border', '1px solid gold')      });             $('#musiccontent').css('background-color', 'black');             $('button').button();         }); //getjsonmusic         $largest = 0;         $(".wrapper").each(function () {             if ($(this).height() > $largest) {                 $largest = $(this).height();             }         });         $(".wrapper").css("height", $largest);     }      function configloading() {         $('#lblloading').show(); // todo: not working reason - configloaded never sets them enabled...         //$('bookdropdown').attr('disabled', true);         //$('moviesdropdown').attr('disabled', true);         //$('musicdropdown').attr('disabled', true);     }      function configloaded() {         $('#lblloading').hide();         //$('bookdropdown').attr('disabled', false);         //$('moviesdropdown').attr('disabled', false);         //$('musicdropdown').attr('disabled', false);     }          $(document).ready(function () {             $('#tabs').tabs({                 beforeactivate: function (event, ui) {                     // pulitzers loaded @ first; time books tab clicked, there                     if (ui.newtab.index() == 1) {                         moviescontent = $('#moviescontent').html();                         if (moviescontent == 'content in movies tab') {                             // todo: when it's ready, uncomment this: getoscars();                         }                     }                     else if (ui.newtab.index() == 2) {                         musiccontent = $('#musiccontent').html();                         if (musiccontent == 'content in music tab') {                             // todo: when it's ready, uncomment this: getgrammies();                         }                     }                 }             });              $('body').on('error', 'img', function (e) {                 $(e.currenttarget).attr("src", "content/noimageavailable.png");             });              // makes external hrefs / targets "pop up"; don't think want that...             //$('body').on('click', 'a', function () {             //    open(this.href, 'newwin', 'toolbar=yes')             //    self.focus();             //    return false;             //});              // books tab default view; load default list (pulitzer); other 2 default lists (oscars , grammies)             // load first time user selects corresponding tab (see beforeactivate() above)             getpulitzers();             currentbookselection = "pulitzer";             configloaded();              $('#bookdropdown').change(function () {                 // todo: may want keep track of when in loading mode, , if so, exit/return                 configloading();                 $('#body').removeclass('bronzebackground silverbackground goldbackground').addclass('bronzebackground');                 var sel = this.value;                 if ((sel == "nbcc") && (currentbookselection != "nbcc")) {                     getnatlbookcritics();                     currentbookselection = "nbcc";                 }                 else if ((sel == "nba") && (currentbookselection != "nba")) {                     getnatlbook();                     currentbookselection = "nba";                 }                 else if ((sel == "noba") && (currentbookselection != "noba")) {                     getnoba();                     currentbookselection = "noba";                 }                 else if ((sel == "pulitzer") && (currentbookselection != "pulitzer")) {                     getpulitzers();                     currentbookselection = "pulitzer";                 }                 configloaded();             }); //bookdropdown              $('#moviesdropdown').change(function () {                 configloading();                 $('#body').removeclass('bronzebackground silverbackground goldbackground').addclass('silverbackground');                 var sel = this.value;                 if ((sel == "oscars") && (currentmovieselection != "oscars")) {                     currentmovieselection = "oscars";                     getmovies('content/oscars.json');                 }                 else if ((sel == "goldenglobe") && (currentmovieselection != "goldenglobe")) {                     currentmovieselection = "goldenglobe";                     getmovies('content/goldenglobe.json');                 }                 else if ((sel == "cannes") && (currentmovieselection != "cannes")) {                     currentmovieselection = "cannes";                     getmovies('content/cannes.json');                 }                 else if ((sel == "sundance") && (currentmovieselection != "sundance")) {                     currentmovieselection = "sundance";                     getmovies('content/sundance.json');                 }                 configloaded();             }); //moviesdropdown              $('#musicdropdown').change(function () {                 configloading();                 $('#body').removeclass('bronzebackground silverbackground goldbackground').addclass('goldbackground');                 var sel = this.value;                 if ((sel == "grammies") && (currentmusicselection != "grammies")) {                     currentmusicselection = "grammies";                     getgrammies();                 }                 else if ((sel == "ama") && (currentmusicselection != "ama")) {                     currentmusicselection = "ama";                     getama();                 }                 else if ((sel == "cma") && (currentmusicselection != "cma")) {                     currentmusicselection = "cma";                     getcma();                 }                 else if ((sel == "indies") && (currentmusicselection != "indies")) {                     currentmusicselection = "indies";                     getindies();                 }                 configloaded();             }); //musicdropdown              // added 7/24/2013, changed nothing             //$(function() {             //    $('a').click(function() {             //        open(this.href, 'newwin', 'toolbar=yes');             //        self.focus();             //        return false;             //    });             //});          }); //ready </script> 

update 8

barvaz's answer not work me; maybe i'm doing wrong? based on answer, added:

css

.noimg {   background:url(~/content/noimageavailable.png);     } 

jquery

0) added within ready handler:

replaceemptyimage = function ($img) {     $img.parent().addclass('noimg');     $img.remove(); }; 

1) changed line:

datapoint.imghref + '\"' + ' target=\"_blank\"><img height=\"160\" width=\"107\" src=\"' + 

...to this:

datapoint.imghref + '\"' + ' target=\"_blank\"><img height=\"160\" width=\"107\" onerror=\"replaceemptyimage($(this))\" src=\"' + 

update 9

here's looks (the image "block" or "object" there, it's it's black/blank):

enter image description here

btw, travels of jamie mcpheeters awesome book @ rate, perhaps read kids (any age, perhaps pre-teen optimal).

use images loaded plugin

https://github.com/desandro/imagesloaded

leverages jquery deferred objects awesomeness. handle figuring out whether image loaded you, dont have use jquery.error (tbh, that's not appropriate use that).


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -