Is there any way to render a default image in an HTML tag, in case the
src
attribute is invalid (using only HTML)? If not, what would
For any image, just use this javascript code:
if (ptImage.naturalWidth == 0)
ptImage.src = '../../../../icons/blank.png';
where ptImage
is a <img>
tag address obtained by document.getElementById()
.
<style type="text/css">
img {
background-image: url('/images/default.png')
}
</style>
Be sure to enter dimensions of image and whether you want the image to tile or not.
Simple and neat solution involving some good answers and comment.
<img src="foo.jpg" onerror="this.src='error.jpg';this.onerror='';">
It even solve infinite loop risk.
Worked for me.
A modulable version with JQuery, add this at the end of your file:
<script>
$(function() {
$('img[data-src-error]').error(function() {
var o = $(this);
var errorSrc = o.attr('data-src-error');
if (o.attr('src') != errorSrc) {
o.attr('src', errorSrc);
}
});
});
</script>
and on your img
tag:
<img src="..." data-src-error="..." />
The above solution is incomplete, it missed the attribute src
.
this.src
and this.attribute('src')
are NOT the same, the first one contains the full reference to the image, for example http://my.host/error.jpg
, but the attribute just keeps the original value, error.jpg
Correct solution
<img src="foo.jpg" onerror="if (this.src != 'error.jpg' && this.attribute('src') != 'error.jpg') this.src = 'error.jpg';" />
This works well for me. Maybe you wanna use JQuery to hook the event.
<img src="foo.jpg" onerror="if (this.src != 'error.jpg') this.src = 'error.jpg';">
Updated with jacquargs error guard
Updated: CSS only solution
I recently saw Vitaly Friedman demo a great CSS solution I wasn't aware of. The idea is to apply the content
property to the broken image. Normally :after
or :before
do not apply to images, but when they're broken, they're applied.
<img src="nothere.jpg">
<style>
img:before {
content: ' ';
display: block;
position: absolute;
height: 50px;
width: 50px;
background-image: url(ishere.jpg);
</style>
Demo: https://jsfiddle.net/uz2gmh2k/2/
As the fiddle shows, the broken image itself is not removed, but this will probably solve the problem for most cases without any JS nor gobs of CSS. If you need to apply different images in different locations, simply differentiate with a class: .my-special-case img:before { ...