Hide broken images jQuery

D_Guy13 picture D_Guy13 · Jul 29, 2013 · Viewed 13k times · Source

I have content with broken images, multiple images in each page. Some images have empty src value and some just broken 404 links.

I have been trying to use

<script type="text/javascript">
$(document).ready(function () {
    $("img").error(function(){
    $(this).hide();
    });
}); 
</script>

It doesn't work as expected, doesn't work in IE, and in chrome I have to reload the page after first load to hide the images. Googled a lot, but all other codes are the same.

Editing the <img> tag is NOT an option for me.

What is wrong with that code?

Answer

Telvin Nguyen picture Telvin Nguyen · Jul 29, 2013

Use it instead

<img src="image.png" onError="this.onerror = '';this.style.visibility='hidden';" />

test

or you can do it for all of your images

$(window).load(function() { 
   $("img").each(function(){ 
      var image = $(this); 
      if(image.context.naturalWidth == 0 || image.readyState == 'uninitialized'){  
         $(image).unbind("error").hide();
      } 
   }); 
});

demo