Categories
JavaScript Answers

How to show alternate image if source image is not found with JavaScript?

Spread the love

Sometimes, we want to show alternate image if source image is not found with JavaScript.

In this article, we’ll look at how to show alternate image if source image is not found with JavaScript.

How to show alternate image if source image is not found with JavaScript?

To show alternate image if source image is not found with JavaScript, we can listen to the error event of the img element.

For instance, we write

const img = document.getElementById("myImage");
img.onerror = () => {
  img.src = "alternate.png";
};

to get the img element with getElementById.

Then we set img.onerror to a function that runs when the error event is triggered by the img element.

The event will be triggered if the image fails to load.

In the function, we set the src property of the img element to an alternative image URL.

Conclusion

To show alternate image if source image is not found with JavaScript, we can listen to the error event of the img element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *