1

I am trying to detect if the image is available in javascript.

I have a switch statement which return different type of images.

switch (type){

case 'oldProduct':
return "<img src='project/'" + folder + imagename + "/>"
break;

case 'newProduct':
return "<img src='project/'" + folder2 + imagename2 + "/>"
break;

more cases....

}

I was wondering if there are anyways to detect if the images exist before I return the image. <img src='project/'" + folder2 + imagename2 + "/img> src could be a broken path in my case. Thanks a lot!

Rouge
  • 4,181
  • 9
  • 28
  • 36
  • So you need to detect if image is served or not from server with specifed path right? – WooCaSh May 02 '13 at 17:07
  • 1
    You can download an image in JS, e.g. via $.get (jQuery) and check the status of the response. – Grigorii Chudnov May 02 '13 at 17:11
  • @WooCaSh yes that is correct. – Rouge May 02 '13 at 17:13
  • 2
    http://stackoverflow.com/questions/9809015/image-onerror-event-never-fires-but-image-isnt-valid-data-need-a-work-around - create a `new Image()` dynamically, set its `src` property, use the `load` event, and check its height/width – Ian May 02 '13 at 17:15
  • 2
    I'm assuming the `/img>` at the end of your `img` tag is a typo? – Brigham May 02 '13 at 17:18

1 Answers1

2

If you just wanted to use javascript and not jquery my only suggestion would be to load the image onto the page like

<img src="yoursrc" id="testImage" style="display:none;"/>

then check the onerror method "not may not work in really old ie"

var image = document.getElementById('testImage');
im.onerror = function(){
  //do something on error
};

However a much neater and reliable way would be to run a jquery get on the image.

Like this

function checkImg(src){
   var jqxhr = $.get(src, function() {
     return true;
   }).fail(function() { 
    return false;
   });
}
Dominic Green
  • 10,142
  • 4
  • 30
  • 34