12

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.

Rod Johnson
  • 2,387
  • 6
  • 30
  • 48

4 Answers4

18

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

meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
  • Is it working in all browsers? Related info is missing in https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror – MilesDyson Oct 14 '19 at 15:23
6

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
  • 5,709
  • 2
  • 29
  • 52
5

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

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

Robert
  • 21,110
  • 9
  • 55
  • 65
0

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
  • 5,039
  • 4
  • 40
  • 62
  • 2
    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 Aug 16 '10 at 17:02
  • this should be `img.target.src = default.gif` – David Odinaka Enyoghasim Nov 08 '21 at 05:40