Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to detect broken images in javascript? [duplicate]

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.

like image 274
Rod Johnson Avatar asked Aug 16 '10 16:08

Rod Johnson


2 Answers

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

like image 109
meder omuraliev Avatar answered Oct 25 '22 10:10

meder omuraliev


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>
like image 29
mhitza Avatar answered Oct 25 '22 09:10

mhitza