How to check if image exists with given url?

jquery

Solution

Use the `error` handler like this:

$('#image_id').error(function() {
  alert('Image does not exist !!');
});

If the image cannot be loaded (for example, because it is not present at the supplied URL), the alert is displayed:

Update:

I think using:

$.ajax({url:'somefile.dat',type:'HEAD',error:do_something});

would be enough to check for a 404.

More Readings:

- http://www.jibbering.com/2002/4/httprequest.html

- http://www.ibm.com/developerworks/web/library/wa-ajaxintro3/

Update 2:

Your code should be like this:

$(this).error(function() {
  alert('Image does not exist !!');
});

No need for these lines and that won't check if the remote file exists anyway:

var imgcheck = imgsrc.width;    

if (imgcheck==0) {
  alert("You have a zero size image");
} else { 
  //execute the rest of code here 
}

Problem

I want to check if an image exists using jquery. For example how do I check this image exists ``` http://www.google.com/images/srpr/nav_logo14.png ``` the check must give me a 200 or status ok --------------edited------------------- ``` var imgsrc = $(this).attr('src'); var imgcheck = imgsrc.width; if (imgcheck==0) { alert("You have a zero size image"); } else { //do rest of code } ``` Thanks Jean

Original source