Hide or change all broken or invalid images

If you would like to check all images (<img /> tag) on your site and hide them in case, their src attribute points to an invalid location, then there’s a great solution for this on Stack Overflow. I have added a very little fix to that code, to have images replaced with some default one, instead of being hidden.

For a single image you can do something as easy as (from mentioned SO answer):

[code language=”html”]
<img src="image.png" onError="this.onerror = ”;this.style.visibility=’hidden’;" />
[/code]

You can use jQuery to browse all images in your DOM document:

[code language=”javascript”]
$("img").each(function()
{
var image = $(this);

if(image.context.naturalWidth == 0 || image.readyState == ‘uninitialized’)
{
$(image).unbind("error").hide();
}
});
[/code]

Replace:

[code language=”javascript”]
$(image).unbind("error").hide();
[/code]

with:

[code language=”javascript”]
$(image).src = ‘/images/general-no-preview.jpg’;
$(image).unbind("error");
[/code]

to have invalid images replaced with some default one, instead of being hidden.

There is a pure Javascript / no-jQuery alternative to above code:

[code language=”html”]
<img src="image.png" onerror="onImageError(this);"/>
[/code]

[code language=”javascript”]
function onImageError(image) {
image.onerror = "";
image.src = "/images/general-no-preview.jpg";
return true;
}
[/code]

Which can be also reduced to a oneliner:

[code language=”html”]
<img src="image.png" onError="this.onerror=null;this.src=’/images/general-no-preview.jpg’;" />
[/code]

All above examples bases on error event, which is fired, when browser encounters an image, that does not exist. This event is supported by all major browsers.

Leave a Reply