Do you know how to hide the classic “Image not found” icon from a rendered HTML page when an image file is not found?
Is it feasible with JavaScript\jQuery\CSS?
Do you know how to hide the classic “Image not found” icon from a rendered HTML page when an image file is not found?
Is it feasible with JavaScript\jQuery\CSS?
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.
Andy's reply is correct, however, you might want to use style.vsibility instead.
If you set visibility, the element still keeps its space on your document, thus no funny document movements.
Doing a quick research on Andy E's answer, its not possible to live()
bind error
.
// won't work (chrome 5)
$('img').live('error', function(){
$(this).css('visibility', 'hidden');
});
So you have to go like
$('<img/>', {
src: 'http://www.notarget.com/fake.jpg',
error: function(e){
$(this).css('visibility', 'hidden');
}
}).appendTo(document.body);
directly binding the error event handler
on creating a new element.
All images: javascript( you add this script 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 not affected
}
}
})();