Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript check if img src is valid? [duplicate]

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?

like image 941
kiasecto Avatar asked Aug 17 '10 06:08

kiasecto


3 Answers

Put this in the image tag:

onError="image_error(this.id)"

which will pass the id of the image to image_error function.... duh

like image 23
kiasecto Avatar answered Oct 24 '22 01:10

kiasecto


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. ​

like image 90
Christian C. Salvadó Avatar answered Oct 24 '22 00:10

Christian C. Salvadó


Adding the onError attribute is indeed the correct way to handle it. In your case, you'd add something like:

var myPicture = document.getElementById('MyPicture');
myPicture.onError = errorHandler();

function errorHandler(msg,file_loc,line_num) {
  myPicture.src = 'http://www.google.com/intl/en_ALL/images/srpr/logo1w.png';
}
like image 1
Raul Agrait Avatar answered Oct 24 '22 02:10

Raul Agrait