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?
4 Answers
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/
6 Comments
Yahel
This doesn't seem to work for me... jsfiddle.net/UzEKZ/1 ; The documentation makes it sound like it only hides the broken image icon for IE users.
phil crowe
hi this doesnt work for me either. just wondering would this just hide the image instead of the parent div?
phil crowe
hi got it to work, $(".userFeatureProductImage img").error(function () { $(this).parent().hide(); });
Jonathon Bolster
Hi - not entirely certain why this is the case. I've added a working example, but for some reason it doesn't work correctly when I have it in the 'JavaScript' box. Possible because the event is raised before. I've also updated it to hide the parent div.
Jonathon Bolster
Ahh - it wasn't working in jsFiddle but when I changed the wrap to onDomReady, it worked.
|
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.