0

I have just downloaded Snap SVG and I'm trying to figure out how to display an image with a fall back arrangement. Here is the code:

var s = Snap("#MyPopup");
var g = s.g();
var image = g.image("http://myimages.com/xyz.png", 250, 10, 40,40 );

This displays the image perfectly. However, if the image is missing then you get that broken image-not-fond icon. Instead of that I want to display an alternate image, say http://myimages.com/abc.png , if the primary image is not found (similar to onerror used with <img>). Can someone please guide me how to do that.

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
AnR
  • 1,809
  • 3
  • 26
  • 45
  • 1
    You want to check to make sure the image exists, and then display it only if it exists. See here: http://stackoverflow.com/questions/18837735/check-if-image-exists-on-server-using-javascript -- check for the image, then wrap your g.image statement in an if statement and display the replacement image if the first one is not found. – AustinC Oct 13 '16 at 14:19
  • Thanks @AustimC. That was helpful indeed. – AnR Oct 13 '16 at 16:29

1 Answers1

1

Taking cue from @AustinC I have slightly modified the solution given at Check if image exists on server using JavaScript? that he suggested.

Basically the suggested function was returning 403 (instead of 404) as my images were hosted at amazon cloud, hence I opted to check return code 200 (OK). Here is the final solution.

var s = Snap("#MyPopup");
var image = null;
var mImagePath = "https://myimages.com/xyz.png";

if ( imageExists (mImagePath) == true ) {
    image = s.image(mImagePath, 250, 10, 40,40 );                   
} else {
    image = s.image("https://myimages.com/ImageNotFound.png", 250, 10, 40,40 );
}


function imageExists(image_url){

    var http = new XMLHttpRequest();

    http.open('HEAD', image_url, false);
    http.send();

    return http.status == 200;

}
Community
  • 1
  • 1
AnR
  • 1,809
  • 3
  • 26
  • 45