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).
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
<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
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.
🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉