team
team

Reputation: 59

How to handle image not found error in html5 picture tag

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?

Upvotes: 2

Views: 3066

Answers (2)

muserref
muserref

Reputation: 361

<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>

Upvotes: 2

clabe45
clabe45

Reputation: 2454

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'.

Upvotes: 0

Related Questions