How to Detect Broken/Unloaded (Error) Images with CSS

Is it possible to detect broken/unloaded (error) images with CSS?

There is no way in CSS specs or drafts, but Firefox has a proprietary selector (pseudo-class) :-moz-broken. Its documentation is very concise and it says “intended for use mainly by theme developers”, but it can be used e.g. as follows:

:-moz-broken { outline: solid red }
:-moz-broken:after { content: " (broken image)" }

Although the documentation says that it “matches elements representing broken image links”, it actually matches broken images (an img element where the src attribute does not refer to an image), whether they are links or not. Presumably, “links” really means “references” here.

CSS 2.1 says: “This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.” But Selectors Level 3 (CSS3 Selectors) just says about them: “They are explained in CSS 2.1.” In practice, browsers handle them differently. Oddly enough, Firefox supports :-moz-broken:after but ignores :-moz-broken:before. It does not support either of these pseudo-elements for normal images, but img:after, too, is supported for a broken image (i.e., the specified content appears after the alt attribute value).

Replace Unavailable Images via CSS?

This works without CSS:

<img src="some.jpg" onerror="this.src='alternative.jpg';">

It seems to even work when Javascript is disabled.

How do i remove broken image box?

use alt here for fallback

demo

html

<img src="abc" alt="image" />

css

img {
width:200px;
height:200px;
}

Alternatively, if you dont want to show any alt text, just give a blank space.

demo here

HTML

<img src="abc" alt=" " />

Check if an image is loaded (no errors) with jQuery

Another option is to trigger the onload and/or onerror events by creating an in memory image element and setting its src attribute to the original src attribute of the original image. Here's an example of what I mean:

$("<img/>")
.on('load', function() { console.log("image loaded correctly"); })
.on('error', function() { console.log("error loading image"); })
.attr("src", $(originalImage).attr("src"))
;

Hope this helps!

How to detect image load failure and if fail, attempt reload until success?

Here something I compiled which might help. I couldn't manage to do testing of this please let me know if you are having any issues.

$(function() {
var $images = $('img.imageClassUpdateAtInterval:not([src="/assets/spinner.gif"])');

// Now, no such image with
// a spinner
if($images.length === 0 && window.imageLocator)
clearInterval(window.imageLocator);

window.imageLocator = setInterval(function() {
$images.each(function() {
$this = $(this);
if (!$this.data('src')) {
$this.data('src', $this.prop('src'));
}

$this.prop('src', $this.data('src') + '?timestamp=' + new Date().getTime());
console.log($this.prop('src'));
});
}, 60 * 1000);

// suppose, an error occured during
// locating the src (source) of the
// image - image not found, network
// unable to locate the resource etc.
// it will fall in each time on error
// occurred
$('img.imageClassUpdateAtInterval').error(
function () {
// set a broken image
$(this).unbind("error").attr("src", "/assets/broken.gif");
// setting this up in relative
// position
$(this).css("position", "relative");
$(this).apppend("<span>Error occured</span>");
$(this).find("span").css({"position": "absolute", "background-color": "#252525", "padding": ".3em", "bottom": "0"});
});

});

The above solution is compiled from two different solutions commenced by @user113716 and @travis

Hide li if broken image

You can use an onerror handler for the image:

<li><a href='http://www.so.com'>
<img src='http://www.so.com/1.jpg' onerror='hideContainer(this)'>
</a></li>

// this function must be in the global scope
function hideContainer(el) {
$(el).closest("li").hide();
}

Or, you could even just remove it if you really want it as if it never existing in the DOM:

// this function must be in the global scope
function hideContainer(el) {
$(el).closest("li").remove();
}

If you don't want to put an onerror handler in the HTML (the only reliable place you can put it) then you can hide the images initially and then check .complete when your jQuery runs and if the image is not yet complete, then install a .load() handler like this:

CSS:

/* use some more specific selector than this */
li {display: none;}

jQuery:

$("li img").each(function() {
if (this.complete) {
// img already loaded successfully, show it
$(this).closest("li").show();
} else {
// not loaded yet so install a .load handler to see if it loads
$(this).load(function() {
// loaded successfully so show it
$(this).closest("li").show();
});
}
});

Detect when an image fails to load in JavaScript

You could try the following code. I can't vouch for browser compatibility though, so you'll have to test that.

function testImage(URL) {
var tester=new Image();
tester.onload=imageFound;
tester.onerror=imageNotFound;
tester.src=URL;
}

function imageFound() {
alert('That image is found and loaded');
}

function imageNotFound() {
alert('That image was not found.');
}

testImage("http://foo.com/bar.jpg");

And my sympathies for the jQuery-resistant boss!



Related Topics



Leave a reply



Submit