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?
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?
Share Improve this question asked Feb 26, 2015 at 10:53 DancerDancer 17.7k40 gold badges131 silver badges213 bronze badges 2- You should probably perform this check at the end of the document after the whole page is loaded. – Karan Commented Feb 26, 2015 at 11:05
- Take a look at this link : stackoverflow./questions/3381663/… – ggg Commented Feb 26, 2015 at 11:05
3 Answers
Reset to default 4function IsValidImageUrl(url) {
$("<img>", {
src: url,
error: function() { alert(url + ': ' + false); },
load: function() { alert(url + ': ' + true); }
});
}
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");
}
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;