Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 don't want to show any error picture. This is my code but it doesn't work.

html

<div id=test>
    <img src="http://test.com/test1.jpg" />
    <img src=" http://test.com/test2.jpg" />
    <img src="http://test.com/test3.jpg" />
</div>

jquery

var pic_list = jQuery("#test img");

pic_list.load(function () {
    var http = new XMLHttpRequest();
    http.open('HEAD', pic_list, false);
    http.send();
    if (http.status == 404) {
        pic_list.hide();
    } else {
        pic_list.show();
    }
});
like image 234
user1761824 Avatar asked Oct 21 '12 02:10

user1761824


People also ask

How can check image exist or not in jquery?

Use the error handler like this: $('#image_id'). error(function() { alert('Image does not exist !! '); });


1 Answers

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:

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

JS:

function imgError(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.

like image 50
Fabrício Matté Avatar answered Sep 27 '22 21:09

Fabrício Matté