Default images

by Dmytro Tsiniavskyi

HTML

<img id="1" src="error" data-default-src="https://dl.dropboxusercontent.com/u/765818/images/error.png" />
<img id="2" src="error" data-default-src="https://dl.dropboxusercontent.com/u/765818/images/error.png" />
<img id="3" src="error" data-default-src="https://dl.dropboxusercontent.com/u/765818/images/error.png" />
<img id="4" src="error" data-default-src="https://dl.dropboxusercontent.com/u/765818/images/error.png" />
<img id="5" src="error" data-default-src="https://dl.dropboxusercontent.com/u/765818/images/error.png" />

CSS

img{
    width: 320px;
    height: 240px;
    margin: 2px;
    padding: 2px;
    border: 1px solid black;
}

JavaScript

$(window).load(function () {
    $('img').each(function () {
        if (IsBroken(this)) {
            var defaultSrc = $(this).data('default-src');
            if (defaultSrc != undefined) this.src = defaultSrc;
        }
    });
});

function IsBroken(image) {
    return !image.complete || typeof image.naturalWidth == 'undefined' || image.naturalWidth == 0 || image.readyState == 'uninitialized';
}

/* This solution works here
$(document).ready(function () {
    $('img').each(function () {
        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
            // image was broken, replace with your new image
            this.src = $(this).data('default-src');
        }
    });
});*/