Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether an image exists, if not set a default image using Javascript

I have a lot of images. like:

<img src="src1"/>
<img src="src2"/>
<img src="src3"/>

Some of the image maybe do not exist. So the browser will show a broken image picture. It is ugly. How to use Javascript not jQuery to determine whether an image exists? If not, give a local image to replace it. Thank you.

I tried the code , it replaced all the images not only those not exist.

function imgError(image) {
            image.onerror = "";
            image.src = "http://www.hi-pda.com/forum/uc_server/data/avatar/000/85/69/99_avatar_middle.jpg?random=10.20420048222877085";
            return true;
        }

        var imgs = document.getElementsByTagName("img");
        for (var i = 0; i < imgs.length; i++) {
            imgs[i].onerror=imgError(imgs[i]);
        }

the images are

<img src="rrrrr"  />
    <img src="http://www.hi-pda.com/forum/uc_server/data/avatar/000/52/56/39_avatar_middle.jpg"/>

the first picture does not exist , the second one exists. when I run it in chrome , all the picture were replaced...

like image 974
leizh00701 Avatar asked Jul 21 '26 16:07

leizh00701


1 Answers

Simple solution:

<img src="http://src1/img.jpg" onerror="this.src='http://src1/error-img.jpg';">

Set within the img tag

Update

A better solution which stops infinite loops - thanks @stom

<img src="foo.jpg" onerror="if (this.src != 'error.jpg') this.src = 'error.jpg';">

Originally posted by @svend here

like image 109
StudioTime Avatar answered Jul 24 '26 07:07

StudioTime



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!