Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 859
systempuntoout Avatar asked Jul 13 '10 09:07

systempuntoout


People also ask

How do you hide image not found icon when source image is not found?

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.

How hide image if SRC is empty?

HTML allows to use the onerror event on images to hide them when the src URL returns a 404, or when it's undefined or null . In React, you can use the onError event to prevent 404 errors.

How do you show an alternate image if source image is not found?

You simply need to add class='backup_picture' to any img tag that you want a backup picture to load if it tries to show a bad image.

How do I make an image invisible in HTML?

Hiding an Image in CSS The trick to hiding any element on your web page is to insert either a " display: none; " or " visibility: hidden; " rule for that element. The " display: none; " rule not only hides the element, but also removes it from the document flow.


3 Answers

<img onerror='this.style.display = "none"'>
like image 79
Gary Willoughby Avatar answered Oct 17 '22 22:10

Gary Willoughby


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.

like image 106
Andy E Avatar answered Oct 17 '22 21:10

Andy E


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

like image 12
Sash Avatar answered Oct 17 '22 22:10

Sash