jQuery: Check if image exists

Marko picture Marko · Jul 25, 2010 · Viewed 44.8k times · Source

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?

Answer

Reigel picture Reigel · Jul 25, 2010

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

like this,

$(".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...