Skip to content Skip to sidebar Skip to footer

Jquery To Check Image Exists If Head 404 Than Hide It

Using php to get 100 photos url from a db and show them on a page, but some photos may no longer exist. If the photo url is fail (404) I want to use jquery to hide the image and do

Solution 1:

Sending multiples ajax requests is unnecessary when you can use the onerror event.

Check out the related jQuery/Javascript to replace broken images post.

Adapting that to your needs:

HTML:

<imgsrc="someimage.png"onerror="imgError(this);" />

JS:

functionimgError(image){
    image.style.display = 'none';
}

Fiddle

Or with jQuery:

function imgError(image){
    $(image).hide();
}

I normally wouldn't use inline JS in the HTML, and even considered using an .error handler:

$('#test img').error(function() {
    $(this).hide();
});

But the above will not work if the handler attaching is executed after the error event has fired, hence I suggest the first solution.

Solution 2:

The second parameter of the open method is a url, not an array of HTML elements.

So you can use each to iterate over the elements, get their src attribute using .attr() and pass that into the method.

Since you have the images loaded already, instead of doing another request for each one, you might be able to use a method I discussed in another question: Check if user is blocking 3rd party domain

If your images aren't of fixed height/width, a non-existent image will produce a small icon indicating the image doesn't exist. You can use the size of the image to see if the image was loaded or not.

Post a Comment for "Jquery To Check Image Exists If Head 404 Than Hide It"