Reputation: 1080
Is there a way to use onError twice if the first onError doesn't exist
<img class="media-object img-responsive" src="/img/product/{{ product_type_slug }}/thumb/{{ image_thumb }}" alt="{{ name }}"
onError="
this.onerror=null;
this.src='/img/product/swatch/{{ image }}';">
Looking for an onError for the onError to show:
src='/img/product/{{ product_type_slug }}/old/{{ image_thumb }}'
so if the original image doesnt exist show swatch url, if that doesnt exist show old.
Upvotes: 2
Views: 2039
Reputation: 4187
You could use a javascript function to deal with this scenario
function loadAlternative(element, list) {
var image = new Image();
image.onload = function() {
element.src = this.src;
}
image.onerror = function() {
if (list.length) {
loadAlternative(element, list);
}
}
// pick off the first url in the list
image.src = list.shift();
}
<img src="nope.jpg"
data-alternative="njet.jpg,neither.jpg,http://lorempixel.com/400/200/technics/1/"
onerror="loadAlternative(this, this.getAttribute('data-alternative').split(/,/))">
What this does:
data-alternative
attributeonerror
is triggered, the loadAlternative
function is called with both the element (img
) and the data-alternative
list as arraysrc
on the element
If you need some default image to be used should all alternatives fail, you could modify the image.onerror
function to deal with an empty list like this:
image.onerror = function() {
if (list.length) {
loadAlternative(element, list);
}
else {
element.src = '/every/other/option/has/failed.jpg';
}
}
Please note that you could (on the web this means: you will) end up with a lot of attempts to load images, which may be prevented by having the server check for the existence of images.
Upvotes: 2