I have a list of images where each image is wrapped in a li:
<li><a href='http://www.so.com'><img src='http://www.so.com/1.jpg'></a></li>
How can I hide this entire li if image 1.jpg is broken as if it never existed in the DOM?
I found some good js on how to hide the image and learned from another SO post that I want to display:none
so I don't create an empty row. But I'm having trouble putting these together.
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.
JavaScript and jQuery can be used to hide the “Image Not Found”icon when the image is not found.
1. Use alt and title attributes in the <img> tag. One big problem with missing images is that the reader has no idea what the missing image was supposed to communicate, which can lead to problems with comprehension on your site. A simple fix for this is to make use of the image attributes for alt text and title.
You can use an onerror
handler for the image:
<li><a href='http://www.so.com'>
<img src='http://www.so.com/1.jpg' onerror='hideContainer(this)'>
</a></li>
// this function must be in the global scope
function hideContainer(el) {
$(el).closest("li").hide();
}
Or, you could even just remove it if you really want it as if it never existing in the DOM:
// this function must be in the global scope
function hideContainer(el) {
$(el).closest("li").remove();
}
If you don't want to put an onerror
handler in the HTML (the only reliable place you can put it) then you can hide the images initially and then check .complete
when your jQuery runs and if the image is not yet complete, then install a .load()
handler like this:
CSS:
/* use some more specific selector than this */
li {display: none;}
jQuery:
$("li img").each(function() {
if (this.complete) {
// img already loaded successfully, show it
$(this).closest("li").show();
} else {
// not loaded yet so install a .load handler to see if it loads
$(this).load(function() {
// loaded successfully so show it
$(this).closest("li").show();
});
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With