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):

<img src="image.png" onError="this.onerror = '';this.style.visibility='hidden'" />

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

$("img").each(function()
{
    var image = $(this);

    if(image.context.naturalWidth == 0 || image.readyState == 'uninitialized')
    {
        $(image).unbind("error").hide();
    }
});

Replace:

$(image).unbind("error").hide();

with:

$(image).src = '/images/general-no-preview.jpg';
$(image).unbind("error");

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

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

<img src="image.png" onerror="onImageError(this);" />
function onImageError(image) {
    image.onerror = "";
    image.src = "/images/general-no-preview.jpg";
    
    return true;
}

Which can be also reduced to a oneliner:

<img src="image.png" onError="this.onerror=null;this.src='/images/general-no-preview.jpg';" />;

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