Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen to the error event of all images?

I want to hide broken images that get loaded dynamically. For static ones, this works.

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

However, when I bind that to the document nothing happens. There is no error in the console, either.

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

How can I listen to errors of images that are loaded dynamically?

like image 295
danijar Avatar asked Mar 19 '14 08:03

danijar


2 Answers

You can do it with the useCapture of addEventListener.

document.addEventListener('error', (e) => {
  // do your magic here
}, true)
like image 157
philfreo Avatar answered Sep 21 '22 18:09

philfreo


The error event does not bubble. The DOM Level 2 Events specifies it should but The DOM Level 3 Events overrides this.

You could try window.onerror but I'm not sure if that only catches run-time script errors in your code or errors thrown by failing resources. If it works it will also catch all errors.

Arun P Johny confirms my doubts, window.onerror is a no-go.

The matter is discussed in error event with live.

A solution could be to add a generic error handler on all images, those loaded dynamicly included. And then have that generic error handler trigger a custom jQuery event, e.g.:

$( 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 );
}
like image 28
anddoutoi Avatar answered Sep 25 '22 18:09

anddoutoi