How to silently hide "Image not found" icon when src source image is not found

91,409

Solution 1

You can use the onerror event in JavaScript to act when an image fails to load:

var img = document.getElementById("myImg");
img.onerror = function () { 
    this.style.display = "none";
}

In jQuery (since you asked):

$("#myImg").error(function () { 
    $(this).hide(); 
});

Or for all images:

$("img").error(function () { 
    $(this).hide();
    // or $(this).css({visibility:"hidden"}); 
});

You should use visibility: hidden instead of .hide() if hiding the images might change the layout. Many sites on the web use a default "no image" image instead, pointing the src attribute to that image when the specified image location is unavailable.

Solution 2

<img onerror='this.style.display = "none"'>

Solution 3

I've slightly modified the solution suggested by Gary Willoughby, because it briefly shows the broken image icon. My solution:

    <img src="..." style="display: none" onload="this.style.display=''">

In my solution image is hidden initially and is shown only when it is successfully loaded. It has a disadvantage: users will not see halfloaded images. And if user has disabled JS then they will never see any images

Solution 4

To hide every image error, just add this JavaScript at the bottom of your page (just before the closing body tag):

(function() {
    var allimgs = document.images;
    for (var i = 0; i < allimgs.length; i++) {
        allimgs[i].onerror = function() {
            this.style.visibility = "hidden"; // Other elements aren't affected. 
        }
    }
})();

Solution 5

It may be little late to answer, but here is my attempt. When I faced the same issue I fixed it by using a div of the size of image & setting background-image to this div. If the image is not found, the div is rendered transparent, so its all done silently without java-script code.

Share:
91,409
systempuntoout
Author by

systempuntoout

I'm a software architect, living and working in Italy. My Google App Engine project: - StackPrinter

Updated on January 21, 2022

Comments

  • systempuntoout
    systempuntoout over 2 years

    Do you know how to hide the classic “Image not found” icon from a rendered HTML page when an image file is not found?

    Any working method using JavaScript/jQuery/CSS?