Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery/javascript - hide div if containing image is broken

i have a div with the class 'userFeatureProductImage'. this div is repeated however occasionally a broken image might come through so i want to hide the div as a precaution if this does happen. how can i do this?

like image 301
phil crowe Avatar asked Dec 14 '10 16:12

phil crowe


3 Answers

The load event is only fired if an image is valid:

$('.userFeatureProductImage').hide();
$('.userFeatureProductImage img').load(function() {
  $(this).closest('.userFeatureProductImage').show();
});
like image 81
Nathan MacInnes Avatar answered Sep 22 '22 06:09

Nathan MacInnes


Use the error event which is called when an error occurs with the image:

$(".userFeatureProductImage img").error(function(){
   $(this).parent().hide();
});

Example: http://jsfiddle.net/jonathon/vWwpc/

like image 33
Jonathon Bolster Avatar answered Sep 26 '22 06:09

Jonathon Bolster


You might try something like this:

<script type="text/javascript" 
        src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
     function hideBrokenImage(id) {
          $(id.+"userFeatureProductImage").hide();
     }
</script>
<div id="imageFilename" class="userFeatureProductImage">
     <img src="imageFilename.gif" onerror="hideBrokenImage(imageFilename);" />
</div>

Where imageFilename is obviously dynamically created.

like image 23
divby1 Avatar answered Sep 22 '22 06:09

divby1