3

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?

Dancer
  • 17,035
  • 38
  • 129
  • 206
  • You should probably perform this check at the end of the document after the whole page is loaded. – Karan Feb 26 '15 at 11:05
  • Take a look at this link : http://stackoverflow.com/questions/3381663/check-if-image-exists-with-given-url-using-jquery – devseo Feb 26 '15 at 11:05

3 Answers3

4
function IsValidImageUrl(url) {
$("<img>", {
    src: url,
    error: function() { alert(url + ': ' + false); },
    load: function() { alert(url + ': ' + true); }
});
}
Rahul G Nair
  • 1,366
  • 10
  • 11
2

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");
}
ptCoder
  • 2,229
  • 3
  • 24
  • 38
1

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;
ares777
  • 3,590
  • 1
  • 22
  • 23