Setting a Fallback Image in HTML for Broken or Missing Images

Displaying images is integral to web design, enhancing user experience and enriching content. However, broken or missing images can hurt your website's appearance and usability.

To fix this issue, you can set a fallback image that will be displayed if the original image is not found or fails to load.

This article will explore setting a fallback image using just HTML (and a bit of inline JS).

A snippet of HTML

Fallback Image in HTML

Using the HTML onerror attribute, you can trigger a function if an image fails to load.

Here is a simple example of how you can set a fallback image using the onerror attribute:

<img src="original_image.jpg" onerror="this.onerror=null; this.src='fallback_image.jpg';" alt="Image description">

In this example, the browser will attempt to load 'original_image.jpg'. If it fails to load, the onerror attribute triggers the JavaScript code specified within it.

This code sets the onerror attribute to null to prevent infinite looping and replaces the 'src' attribute with fallback_image.jpg, which is then loaded.

I've found this very useful for user-uploaded data where there might be missing data or something out of sync.


Follow me on Twitter or connect on LinkedIn.

🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉

JavaScriptHtmlUxWeb Development
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.