Reputation: 457
i want to show images in grid. but if image is not exist i want to show no-image.png. but currently if image is not exist it will show error on console
"GET http://localhost/images/image.png 404 (Not Found)".
i dont want this error if image is not exist. please help me what should i do.. here is my code.
var image = $('<img src="/images/image.png" />');
if (image.attr('width') > 0)
return '/images/No_image.png';
else
return '/images/image.png';
Upvotes: 1
Views: 52
Reputation: 988
you can use below code to check if image exist
function isImageExists(imgSrc, callBackAfterCheck) {
var img = new Image();
img.onload = function() { callBackAfterCheck(true) };
img.onerror = function() {callBackAfterCheck(false) };
img.src = imgSrc;
}
function callBackAfterCheck(status){
if(status == true){
//do your stuff here
console.log('image Exist');
}else{
//do your stuff here
console.log('image not Exist');
}
}
var imageUrl = 'your_image_url';
isImageExists(imageUrl, callBackAfterCheck);
Upvotes: 0
Reputation: 337580
To achieve this you can use the error()
event of the img
element. If that event is raised then you know that the image was not successfully loaded, either from a server error, or a 404. In this case you can then change the src
attribute to your placeholder. Try this:
$('<img src="/images/image.png" />').error(function() {
$(this).attr('src', '/images/No_image.png');
});
Upvotes: 2