I've had an issue for two days and i'm at breaking point. I would like to change the image src
of an image when the image fails to load (image doesn't exist).
In the following example the first two images do exist but yet all of the image src
are replaced by the error event.
https://jsfiddle.net/zq5tsbmj/
var errorHandler = function(imageParsed) {
imageParsed.src = "http://www.theemailcompany.com/wp-content/uploads/2016/02/no-image-placeholder-big-300x200.jpg";
};
var imgs = document.getElementsByTagName("img"),
len = imgs.length;
for (var i = 0, lenImage = len; i < lenImage; i++) {
imgs[i].onerror = errorHandler(imgs[i]);
}
I thought this was because the event was running too quickly. So as per this question I assigned it in an event manner
https://jsfiddle.net/zq5tsbmj/1/
var errorHandler = function(imageParsed) {
imageParsed.src = "http://www.theemailcompany.com/wp-content/uploads/2016/02/no-image-placeholder-big-300x200.jpg";
alert('error');
};
var imgs = document.getElementsByTagName("img"),
len = imgs.length;
for (var i = 0, lenImage = len; i < lenImage; i++) {
imgs[i].onerror = function() {
errorHandler(imgs[i]);
};
}
But this doesn't trigger the error function ever, even though the last image should fail.
Could someone please explain to me what exactly i'm doing wrong. Please don't just provide links to other questions. I would really like to know in simple terms why this code isn't working exactly as expected and what the solution is, otherwise I fear I won't learn from it. Thanks.