replacing 404 image with jQuery
I did a small experiment using jQuery to avoid broken/404 image. This shouldn’t be used regularly but perhaps its a fail safe for some websites which I’m currently working on. Nothing new, just going over basics once again.
One way to avoid having broken image is to check whether the image was successfully loaded by checking img’s naturalWidth|naturalHeight or its readyState(IE). Following code must be executed on window complete event (it maybe a good idea to hide target img on document.ready event).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | var altImage = "images/noimage.jpg"; //path to alternative image var query = "dd.thumb > img"; //selector to img tag. $(document).ready(function(){ $(query).hide(); }); $(window).load(function(){ $(query).each(function(){ if(this.readyState == 'uninitialized' || (typeof this.naturalWidth != "undefined" && this.naturalWidth == 0) ){ $(this).attr('src', altImage) } $(this).fadeIn(); }) }); |
Another way is to use ajax.
This way code can be executed at document.ready.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | $(document).ready(function(){ var query = "dd.thumb"; var altImage = "images/noimage.jpg"; $(query).each(function(){ var url = $.trim($(this).html()); $(this).html(""); var img = new Image(); $(this).append(img); $(img) .load(function(){ $(this).hide(); $(this).fadeIn(); }) .error(function(){ $(this).attr("src", altImage); }) .attr("title", url) .attr("alt", url) .attr("class", "image") .attr("src", url); }); }); |
