Skip to main content

How to Show a Default Image if an Image is Not Found in JavaScript

When an <img> tag's src attribute points to a broken or non-existent link, most browsers will display a disruptive "broken image" icon. For a more professional and user-friendly experience, you should gracefully handle this error by displaying a default fallback image instead. The standard way to achieve this is by listening for the error event on the image element.

This guide will teach you how to use the onerror event to detect a broken image and replace its source with a fallback. You will also learn the critical step of how to prevent an infinite loop if the fallback image itself is also broken.

The Core Method: The error Event

The error event is a standard DOM event that fires on an <img> element if the browser fails to load the image specified in its src attribute. By adding an event listener for this event, we can execute code to correct the problem.

Logic:

  1. Select the <img> element.
  2. Add an error event listener to it.
  3. Inside the event handler function, change the src attribute of the image to the URL of a known, valid fallback image.

Basic Example: Handling a Single Broken Image

This example demonstrates the fundamental technique.

Example of the problem:

<!-- Problem: This image source will result in a 404 error. -->
<img id="user-avatar" src="https://example.com/non-existent-avatar.jpg" alt="User Avatar">

Solution:

let userAvatar = document.getElementById('user-avatar');
let fallbackImageSrc = '/images/default-avatar.png';

userAvatar.addEventListener('error', () => {
console.log('Error loading image. Setting fallback.');

// Set the src to the fallback image
userAvatar.src = fallbackImageSrc;
userAvatar.alt = 'Default user avatar'; // Optional: Update the alt text
});
note

Now, if non-existent-avatar.jpg fails to load, the browser will immediately try to load default-avatar.png in its place.

A Critical Best Practice: Preventing an Infinite Loop

The solution above has a dangerous hidden flaw: what if the fallback image itself is also broken?

If the fallback image fails to load, it will trigger the error event again. This will cause your event handler to run again, which will try to set the src to the broken fallback again, triggering another error, and so on. This creates an infinite loop that can make the browser unresponsive.

Solution: to prevent this, you must remove the error event listener from the element inside the handler itself before you try to set the new src.

let userAvatar = document.getElementById('user-avatar');
let fallbackImageSrc = '/images/default-avatar.png';

let handleError = function() {
console.log('Error loading image. Setting fallback.');

// Set the src to the fallback image
userAvatar.src = fallbackImageSrc;
userAvatar.alt = 'Default user avatar';

// CRITICAL: Remove the error listener to prevent an infinite loop.
// We use `this` to refer to the element that triggered the event.
this.removeEventListener('error', handleError);
};

userAvatar.addEventListener('error', handleError);
note

By removing the listener, you ensure that if the fallback also fails, it will be treated as a final, single error and will not trigger the loop again.

How to Handle Multiple Images on a Page

You can easily apply this logic to all images on a page by selecting them with querySelectorAll() and iterating over them.

let allImages = document.querySelectorAll('img');
let fallbackImageSrc = '/images/default-avatar.png';

let handleError = function() {
this.src = fallbackImageSrc;
this.alt = 'Default image';
this.removeEventListener('error', handleError); // Remove listener from THIS image
};

allImages.forEach(img => {
img.addEventListener('error', handleError);
});
note

This robustly attaches a self-removing error handler to every image on the page, ensuring that any broken image will be gracefully replaced.

Conclusion

Handling broken images is a simple but important part of creating a polished web experience.

  • The standard method is to listen for the error event on an <img> element.
  • Inside the event handler, you can change the element's .src to point to a fallback image.
  • Crucially, you must remove the event listener from within the handler to prevent the risk of an infinite loop if the fallback image is also unavailable.