Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do not show broken images via Onload property

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?

like image 554
Prosto Trader Avatar asked Nov 04 '13 17:11

Prosto Trader


1 Answers

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 );
}
like image 117
antyrat Avatar answered Sep 30 '22 19:09

antyrat