0

I would like to show my own error image when an image cant load successfully.

I thought of a JavaScript function:

<script type="text/javascript">
var images = document.getElementsByTagName("img");
for (var i = 0; i < images.length; i++) {
    images[i].onerror = onErrorImage(images[i]);
}       
function onErrorImage(element){
    element.onerror = null;
    element.src = 'errorImage.png';
}
</script>

But this doesn't work. This turns every image on the page into my own error image.

Is there another simple way to show my own error image on error?

Or is there another way to bind a function to an event like i did on line 4? Because I'm pretty sure the script fails on that line.

Solution may be in jQuery.

j08691
  • 204,283
  • 31
  • 260
  • 272

2 Answers2

3

It should be i guess:

images[i].onerror = function(){onErrorImage(this);}
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
0

There are a lot of ways to do this, I will show you one of them :

You can make all of your images with "fake-src" and load them when the document is ready. Of course you can make a loader till they are downloading. Here is a function I write for you:

    imagesReady = function () {
    var myImgs = document.getElementsByTagName("img");
    for (var i = 0; i < myImgs.length; i++) {
        getImageReady(myImgs[i]);
    };
    function getImageReady(el) {
        var url = el.getAttribute("src-fake");
        var image =  document.createElement("img"); 
        image.onload = function() {
            el.src = url;
            el.style.opacity = 1;
            //this image is ok, that why we put his src to be the fake src
        };
        image.onerror = function (err) {
            console.log("err on load :"+image.src);
            el.src = url;
            //this image fail!
        }
        image.src = url;
    }
}
imagesReady();
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
Tsoko
  • 1