0

I have a couple of images links that don't have any images yet but I know when they are available they will be named pic1 and pic2.jpg so i setup theimage src for img tag. but until the image is available I don't want the red cross for broken image to show up, so i have noimage.jpg icon that should replace the src of all broken image. I am using this and its kinda working but noimage icon replaces the broken image after a quick flash of broken image red cross. Can we prevent the quick flash that does show the red cross broken image thing completely so user only sees the noimage icon..

$("img").error(function () {  
 $(this).unbind("error").attr("src", "noimage.gif"); }); 
Anjana Sharma
  • 4,535
  • 5
  • 37
  • 51

1 Answers1

2

Try this...

$(function() {
    $("img").one("load", function() {
        $(this).show();
    }).each(function() {
        if (this.complete) $(this).load();
    }).error(function () {  
        $(this).unbind("error").attr("src", "noimage.gif");
    }).hide();
});

On document ready it will hide every image and then run the "load" method to show them, whilst also including your error handling code.

Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67
  • It worked. Hope it doesn't create page performance issue, does it? – Anjana Sharma Jan 12 '12 at 18:47
  • The above code isn't anything heavy, so I wouldn't worry about it. If you're talking about 1000s of images then anything you do will have a performance impact. – Reinstate Monica Cellio Jan 12 '12 at 19:34
  • Incidentally, if you did like the idea of images fading in, as mentioned by JohnP, just change the .show() to .fadeIn(interval-in-ms). That may have a performance impact though, as fading of any element takes a lot more effort than a simple show. – Reinstate Monica Cellio Jan 12 '12 at 19:36