jQuery: Check if image exists

I'm loading an image path via jQuery $.ajax and before showing the image I'd like to check if it in fact exists. Can I use the image load/ready event or something similar to determine that the file path is valid?

Having .myimage set to display: none, I'm hoping to do something like

$(".myimage").attr("src", imagePath);
$(".myimage").load(function() {
    $(this).show();
});

Is anything like that possible?


Well, you can bind .error() handler...

Update: In jQuery 3.0 and later:

$(".myimage").on("error", function() {
    $(this).hide();
});

note: .error() was deprecated in jQuery 1.8 and removed in 3.0 but in in older versions you can:

$(".myimage").error(function(){
  $(this).hide();
});

well, yours is okay already with load-event

$(".myimage").load(function() {
    $(this).show();
});

the problem with this is if Javascript was disabled the image will not ever show...


Try:

function urlExists(testUrl) {
 var http = jQuery.ajax({
    type:"HEAD",
    url: testUrl,
    async: false
  })
  return http.status;
      // this will return 200 on success, and 0 or negative value on error
}

then use

if(urlExists('urlToImgOrAnything') == 200) {
    // success
}
else {
    // error
}

An old thread I know but I think it could be improved. I noticed OP having intermittent problems which could be due to loading of the image and error checking simultaneously. It would be better to let the image load first and then check for errors:

$(".myimage").attr("src", imagePath).error(function() {
    // do something
});