Skip to content

Instantly share code, notes, and snippets.

@shanna
Created October 19, 2016 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shanna/579c4301ee879103c93f8eee51370fdf to your computer and use it in GitHub Desktop.
Save shanna/579c4301ee879103c93f8eee51370fdf to your computer and use it in GitHub Desktop.
Broken image JS.
// MIT https://github.com/alexrabarts/jquery-brokenimage minus the jquery.
function BrokenImage(selector, options) {
'use strict';
options = options || {};
var defaults = {
timeout: 2500
};
for (var key in defaults) {
if (!options.hasOwnProperty(key)) {
options[key] = defaults[key];
}
}
var elements = document.querySelectorAll(selector);
Array.prototype.forEach.call(elements, function(image){
if (!image instanceof HTMLImageElement)
return;
image.addEventListener('error', placeholder);
setTimeout(function () {
var test = new Image();
test.src = image.src;
if (test.height === 0) {
placeholder();
}
}, options.timeout);
function placeholder() {
if (options.replacement) {
image.src = options.replacement;
}
else {
image.style.visibility = 'hidden';
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment