Reputation: 4239
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!
Upvotes: 1
Views: 5165
Reputation: 10258
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;
});
}
Upvotes: 2