Handle error in HTML image element

Handle error in HTML image element

In this tutorial, we will see How to handle error in HTML image element using javascript.

How to handle errors in HTML image elements?

When your image HTML element is unable to retrieve and display a picture from a particular source or url, you may want to display a fallback image.

There may be other approaches to solving this issue, but I'll discuss the one that is frequently employed by various websites.

When getting an image from a specified source fails, there is an attribute in the image element called onerror where you can specify a callback code to handle the error.

There are many possible causes of failure. Because of an invalid url, an unavailable resource, a down media server, or security concerns, the image may not be fetched (CORS).

If the error is not handled, the browser will display a broken image. We can therefore handle the problem and provide a nice fallback image to prevent that.

Show fallback image on Error using Javascript:

A fallback image can be displayed in the browser in place of a broken image whenever the <img> element cannot load the image.

<img alt="broken image" src="https://example.com/sample.jpg" />

The incorrect image src or an unreachable image src are two examples of error causes.

In the event that we are unable to load the original image, we must provide several fallback images for a better user experience.

To overcome this issue, we can use the OnError event on the image> tag.

<img alt="broken image" onerror="errorHandler()" src="https://example.com/sample.jpg" id="img"/>
---------
const errorHandler = (error) => {
const img = document.getElementById('img');
img.src = 'https://example.com/dummy.jpg'
}

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment