Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide broken images in IE using jQuery?

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();     
  });    
});
like image 363
newbie Avatar asked Jan 03 '11 06:01

newbie


People also ask

How to hide broken image icon?

Step 1: Reference the image as an object instead of an img. When objects fail they don't show broken icons; they just do nothing. Starting with IE8, you can use object and img tags interchangeably. You can resize and do all the glorious stuff you can with regular images too.

How to hide the image in JavaScript?

To show or hide an image with JavaScript, we can set the style. visibility property of the img element. to add buttons and img elements.

How do I hide an image in HTML?

The hidden attribute hides the <img> element. You can specify either 'hidden' (without value) or 'hidden="hidden"'. Both are valid. A hidden <img> is not visible, but maintains its position on the page.


1 Answers

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/

like image 103
Shadow Wizard Hates Omicron Avatar answered Oct 11 '22 20:10

Shadow Wizard Hates Omicron