How To Load A Default Image In HTML, If Image Is Not Found

When creating HTML pages, it can always happen, that you include images into a page that can not be displayed. There are several reasons for this, for example when there is a typo in the source code or the image file has been moved or deleted.

In this case, using the JavaScript event handler onerror allows you to show an alternative image. This is simply written in the img tag, and catches the error.

The example below shows how to do it: an image file named missing-image.jpg should be inserted. If the image can’t be loaded, the onerror event is fired and loads the file default-image.jpg in the event handler. This could, for example, be a neutral graphic, e.g. with the caption “Image not available”, etc.

<img src="missing-image.jpg" onerror="this.src='default-image.jpg';" alt="Missing Image">

(Visited 33,879 times, 1 visits today)

10 thoughts on “How To Load A Default Image In HTML, If Image Is Not Found”

Leave a Comment