javascript check if img src is valid?

kiasecto picture kiasecto · Aug 17, 2010 · Viewed 36.7k times · Source

I have something like:

document.getElementById('MyPicture').src = 'attempted.png';

If the client cannot get that resource, I would like to replace it with:

document.getElementById('MyPicture').src = 'error.png'

I know I can put onError=function() in the image tag, but how can I pass the Id to onError, so that I can have one onError function that can change the src of any bad pics?

Answer

Christian C. Salvadó picture Christian C. Salvadó · Aug 17, 2010

Yes, you can use the onerror event, on image elements is really widely supported, for example:

var image = document.getElementById('MyPicture');
image.onerror = function () {
  alert('error loading ' + this.src);
  this.src = 'error.png'; // place your error.png image instead
};

image.src = 'non-existing.jpg';

Check an example here. ​