steve Kim steve Kim - 6 months ago 16
jQuery Question

JS check if img is not found

So, I have following js img var.

//Where `img_src` is another variable which actual image file MIGHT or MIGHT NOT exist.
var img_source = "/images/" + img_src;
return '<img src="' + img_source + '">';


Because
img_src
might or might not be available, sometimes I am getting
404 Not Found
error.

If there is no image, then I want to perform another function.

How do I check if the image file is available in this case?

I am trying to avoid showing the img attribute all together if image is not available. Thanks!

Answer

You could use a fallback img like so;

<img onerror="this.onerror=null; this.src='img/fallback.png'" />

To hide the element you can do so like this;

<img onerror="this.onerror=null; this.style.display = 'none'" />
Comments