10

I have tried this code copied from jQuery site, but it fails in IE7/IE8, but works in other browsers. What is wrong with this code, it's from jQuery site(http://api.jquery.com/error/). I'm using jQuery version 1.4.4.

$(document).ready(function(){ 
  $("img").error(function(){
    $(this).hide();     
  });    
});
0

3 Answers 3

13

The problem is that by the time $(document.ready) is executed, the image has already finished loading so the load/error events won't be triggered anymore.

The only way I can think of to bypass this is to reload the image, thus "force" the event to be triggered:

$(document).ready(function(){ 
    $("img").each(function(index) {
        $(this).error(function() {
            $(this).hide();     
        });
        $(this).attr("src", $(this).attr("src"));
  });    
});

It shouldn't be too bad on performance as the images will be taken most probably from the cache, not really reloaded from the server.

Live test case (with cool cats ;)) is available here: http://jsfiddle.net/yahavbr/QvnBC/1/

Sign up to request clarification or add additional context in comments.

4 Comments

in IE, when using error() on an img element, you should bind the error handler before you set the src of the image, or it might not trigger correctly.
@ShadowWizard sorry, my bad, I misunderstood the question and your answer, my issue is slightly different.
@MauricioScheffer cheers, you saved me some minutes lol. Did you post question with your own issue then?
@ShadowWizard I already found it in another question, thanks!
0

Using the above solution will still cause a brief appearance of the 'broken image icon', because there is a latency between error() and hide().

I used the jQuery imagesloaded plugin which allows callback when image successfully loaded. First I set the image to visibility:hidden. Then I set it to visible when it loads successfully:

$('div.target img').each(function(){
  $(this).imagesLoaded(function(){
    $(this).css('visibility','visible');
  })
})

This uses a bit more resource, but will prevent the 'broken image icon' from showing at all. I do not use this site-wide, but only sections where broken image is possible.

Comments

0

In my case in IE8, my replacement image was still not loading. The code below fixed this for me. You might have to play around with the timeout delay, to find out what works best.

setTimeout(function() {
    $("img").each(function () {
        $(this).error(function () {
            $(this).attr("src", "../imageupload/image-failed.png");
        });
        $(this).attr("src", $(this).attr("src"));
    });
}, 100);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.