2

I am trying to use the below piece of code:

<picture>
    <source media="(min-width: 1200px)" srcset="https://example.com/images/abc.jpg?resize=169,169">
    <source media="(min-width: 992px)" srcset="https://example.com/images/cde.jpg?resize=132,132">
    <img src="index_files/red_1.jpg" alt="Red 1">
</picture>

the problem which I am facing is when abc.jpg or cde.jpg is not available it should show a default image say e.g., default.jpg and not even the red_1.jpg I referred to other similar topic in the website but i didnt get to know how to handle the problem with the help of html.

Whether onerrorcould be used in that case, if yes, where and how?

Zak
  • 6,976
  • 2
  • 26
  • 48
team
  • 59
  • 2
  • 12

2 Answers2

2
<picture>
  <source srcSet="image.webp" type="image/webp" />
  <source srcSet="image.jpeg" type="image/jpeg" />
  <source srcSet="image.png" type="image/png" />
  <img srcSet="image.jpg" onError={(e) => {
    e.target.onerror = null;
    e.currentTarget.parentNode.children[0].srcset = e.target.src;
    e.currentTarget.parentNode.children[1].srcset = e.target.src;
    e.currentTarget.parentNode.children[2].srcset = e.target.src;
    e.currentTarget.parentNode.children[3].srcset = e.target.src;
  }} />
</picture>
msefer
  • 331
  • 2
  • 10
0

Yes, use the onerror event. Then, you can simply change the src attribute:

let image = document.querySelector('img');
image.onerror = function() {
  if (this.src === 'default1.png') this.src = 'default2.png';
  else if (this.src !== 'default2.png') this.src = 'default1.png';
}

This will change the src of the image from whatever it was to 'default1.png' and then, if it fires again, to 'default2.png'.

clabe45
  • 2,354
  • 16
  • 27
  • there are two tag and the requirement is that - if 1st tag has error then show default1.jpg and in case of 2nd tag error, show default2.jpg. – team Oct 03 '18 at 18:01
  • i am unable to use your solution in my case. – team Oct 03 '18 at 18:24
  • @team I did edit my answer by simply adding an if-statement. It's just logic at this point – clabe45 Oct 04 '18 at 00:13