I have a site with lots of images. Some of them are missing on the server - deleted by the owner.
If image is not loaded (broken) I want to show placeholder - standard image, that indicates that image is missing.
I dont want to rewrite all templates so I cant add onError property to every image tag, so I cant use this solution: jQuery/JavaScript to replace broken images
Is it possible to write global function that will check all images and replace broken on load?
Yes, as you have jQuery in your tags you can use jQuery for that for example.
Bind onerror
handler to all <img>
nodes:
$( 'img' ).on( 'error', function() {
$( this ).attr( 'src', 'http://path.to.your/image.jpg' );
});
In plain JS this can be done like this:
var images = document.getElementsByTagName( 'img' )
, i, len;
for( var i = 0, len = images.length; i < len; i++ ) {
(function( i ) {
images[ i ].onerror = function() {
images[ i ].onerror = null;
images[ i ].src = 'http://path.to.your/image.jpg';
};
})( i );
}
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