How to listen for error event for all images?

I want to hide broken images that load dynamically. For static, this works.

$('img').error(function() { $(this).css({ 'visibility': 'hidden' }); }); 

However, when I bind this to document , nothing happens. There are also no errors in the console.

 $(document).on('error', 'img', function() { $(this).css({ 'visibility': 'hidden' }); }); 

How can I listen to dynamically loaded image errors?

+6
source share
2 answers

The error event contains no bubble. DOM Level 2 Events indicates what it should, but DOM Level Events overrides this.

You can try window.onerror , but I'm not sure if this only catches script runtime errors in your code or errors caused by resource failures. If it works, it will also catch all errors.

Arun P. Johnny confirms my doubts, window.onerror is not-go.

The issue is discussed in the error event with live .

The solution may be to add a common error handler on all images, including dynamically included ones. And then this general error handler fires a custom jQuery event, for example:

 $( document ).on( 'imgerror', function ( event, originalEvent ) { // originalEvent is the error event } ); function genericImgOnError( event ) { $( event.target ).trigger( 'imgerror', event ); } function getImg( src ) { return $( '<img/>', { src: src, } ).on( 'error', genericImgOnError ); } 
+3
source

You can do this with useCapture addEventListener .

 document.addEventListener('error', (e) => { // do your magic here }, true) 
0
source

All Articles