views:

55

answers:

4

I need to be able to detect if an image is broken and replace with a default image if the image link is broken. I know i could do this with an image proxy, but was hoping to do it on the fly with javascript.

+6  A: 

I believe it's the onerror event of the img element. onerror=function(){} though i've never used it.

meder
A: 

You can use <img onerror='doWhateverFunction()' etc etc

http://msdn.microsoft.com/en-us/library/cc197053(v=VS.85).aspx

Robert
A: 

Example of code:

<script language='javascript'>
function defaultImage(img)
{
    img.onerror = "";
    img.src = 'default.gif';
}
</script>
<img alt="My Image" src="someimage.gif" onerror="defaultImage(this);" />
Jack B Nimble
In the usual case - this will work fine. But I'm fairly sure this will cause an infinite loop if `default.gif` is also broken/not found. That's why in http://stackoverflow.com/questions/92720/jquery-javascript-to-replace-broken-images the AC response set img.onerror to blank in the defaultImage function
Jamie Wong
Good point. I'll change it.
Jack B Nimble
A: 

As any event the onerror will propagate upwards on the DOM, so you could make a generic handler for this type of errors.

<script type="text/javascript">
jQuery(document).bind('error', function(event) {
  console.log(event.target.src);
});
</script>
mhitza