Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide li if broken image

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.

like image 588
Chris Avatar asked Nov 24 '13 02:11

Chris


People also ask

How do I hide the broken picture 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 do you hide image not found icon when source image is not found?

JavaScript and jQuery can be used to hide the “Image Not Found”icon when the image is not found.

How do you handle a broken image in HTML?

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.


1 Answers

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();
        });
    }
});
like image 189
jfriend00 Avatar answered Oct 17 '22 13:10

jfriend00