2

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!

Steve Kim
  • 5,293
  • 16
  • 54
  • 99
  • possible duplicate: http://stackoverflow.com/questions/9022427/see-if-src-of-img-exists – CY_ Jun 01 '16 at 00:01

2 Answers2

7

A jQuery way would be to listen to the error event:

var img = $("<img src='http://no-image.com/' />");

img.on('load', function(e){
    alert('Success!');
}).on('error', function(e) {
    alert('ERROR!');
});

img.appendTo("body");

https://jsfiddle.net/j70oybvy/

In pure JavaScript:

var img = document.createElement('img');

img.src='http://no-image.com/';

img.onload = function(e){
    alert('Success!');
};

img.onerror = function(e) {
    alert('ERROR!');
};

document.body.appendChild(img);

https://jsfiddle.net/j70oybvy/1/

Ricardo Souza
  • 16,030
  • 6
  • 37
  • 69
6

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'" />
Mark
  • 2,061
  • 1
  • 16
  • 26
  • Thank you for the reply. I am trying to avoid showing the img attribute all together if image is not available. Thanks! – Steve Kim Jun 01 '16 at 00:11