HTML If Image Is Not Found

Inputting a default image in case the src attribute of an html img is not valid?

You asked for an HTML only solution...

 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<html lang="en">

<head>
<title>Object Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>

<body>

<p>
<object data="https://stackoverflow.com/does-not-exist.png" type="image/png">
<img src="https://cdn.sstatic.net/Img/unified/sprites.svg?v=e5e58ae7df45" alt="Stack Overflow logo and icons and such">
</object>
</p>

</body>

</html>

What's the valid way to include an image with no src?

While there is no valid way to omit an image's source, there are sources which won't cause server hits. I recently had a similar issue with iframes and determined //:0 to be the best option. No, really!

Starting with // (omitting the protocol) causes the protocol of the current page to be used, preventing "insecure content" warnings in HTTPS pages. Skipping the host name isn't necessary, but makes it shorter. Finally, a port of :0 ensures that a server request can't be made (it isn't a valid port, according to the spec).

This is the only URL which I found caused no server hits or error messages in any browser. The usual choice — javascript:void(0) — will cause an "insecure content" warning in IE7 if used on a page served via HTTPS. Any other port caused an attempted server connection, even for invalid addresses. (Some browsers would simply make the invalid request and wait for them to time out.)

This was tested in Chrome, Safari 5, FF 3.6, and IE 6/7/8, but I would expect it to work in any browser, as it should be the network layer which kills any attempted request.

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

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.



Related Topics



Leave a reply



Submit