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?
You can do it with the useCapture
of addEventListener
.
document.addEventListener('error', (e) => {
// do your magic here
}, true)
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 );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With