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
2010-08-16 16:39:48
A:
You can use <img onerror='doWhateverFunction()' etc etc
http://msdn.microsoft.com/en-us/library/cc197053(v=VS.85).aspx
Robert
2010-08-16 16:43:58
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
2010-08-16 16:47:10
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
2010-08-16 17:02:42
Good point. I'll change it.
Jack B Nimble
2010-08-16 17:53:38
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
2010-08-16 18:37:22