Reputation: 17701
Is it possible to check to see if an img src is valid using jquery?
We have a dynamic site with hundreds of news articles - the majority of which contain images - basically theres a back-end bug and even if there isn't an image currently the image div is displayed - which is causing us a few issues.
<div class="imgBlock">
<img class="newsImg" src="db/imgart/10234.jpg" />
</div>
Is it possible to detect whether the img src is delivering an image via JQuery script?
Upvotes: 3
Views: 5738
Reputation: 3628
Use simple css:
<style type="text/css">
.hidden {
display: none;
{
.visible {
display: block;
}
</style>
then script
var imgDiv = document.getElementById('img1'); //your div id
var imgsrc = "db/imgart/10234.jpg"; //or document.getElementById(img1).getElementsByTagName('img');
var img = new Image();
img.onerror = function (evt){
alert(this.src + " can't be loaded.");
//hide <div>
imgDiv.setAttribute('class', 'hidden');
}
img.onload = function (evt){
alert(this.src + " is loaded.");
//show div
imgDiv.setAttribute('class', 'visible');
}
img.src = imgsrc;
Upvotes: 1
Reputation: 2247
Use the error handler like this:
$(".newsImg").error(function() {
alert("No image");
});
Or
var image = new Image();
image.src = "db/imgart/10234.jpg";
if (image.width == 0) {
alert("No image");
}
Upvotes: 2
Reputation: 1376
function IsValidImageUrl(url) {
$("<img>", {
src: url,
error: function() { alert(url + ': ' + false); },
load: function() { alert(url + ': ' + true); }
});
}
Upvotes: 4