Created
February 15, 2017 13:28
-
-
Save webgodo/b1baf99be3eacf517b61246b28ad202e to your computer and use it in GitHub Desktop.
JS Broken Images Handler - A Simple script to
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function ($) { | |
// @input `containerSelector` - String: a CSS selector which targets container of `<img>` element(s) you want to be replaced in case of error (mostly 404) | |
// @input `imagePath` - String: Absolute/Relative path to image file which would be shown (replaced) | |
window.handleBrokenImage = function (containerSelector, imagePath) { | |
if (!containerSelector) { | |
return false; | |
} | |
imagePath = imagePath || 'https://placeholdit.imgix.net/~text?txtsize=33&txt=webgodo&w=350&h=150'; | |
$(containerSelector) | |
.find("img") | |
// iterate over <img> elements and check if they are loaded properly | |
.each(function (index, item) { | |
var $img = $(item); | |
// get image's original source | |
var src = $(item).attr("src"); | |
var img = document.createElement("img"); | |
img.onerror = function () { | |
$img.attr("src", imagePath); | |
}; | |
img.src = src; | |
}); | |
} | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment