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?
Advertisement
Answer
You can use the onerror
event in JavaScript to act when an image fails to load:
JavaScript
x
5
1
var img = document.getElementById("myImg");
2
img.onerror = function () {
3
this.style.display = "none";
4
}
5
In jQuery (since you asked):
JavaScript
1
4
1
$("#myImg").error(function () {
2
$(this).hide();
3
});
4
Or for all images:
JavaScript
1
5
1
$("img").error(function () {
2
$(this).hide();
3
// or $(this).css({visibility:"hidden"});
4
});
5
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.