steve Kim steve Kim - 11 months ago 41
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 + '">';

might or might not be available, sometimes I am getting
404 Not Found

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!


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; = 'none'" />