Show a default image if image is not found using JavaScript

avatar

Borislav Hadzhiev

Fri Jan 07 20222 min read

Show a default image if image is not found using JavaScript #

To show a default image if the original image is not found:

  1. Add an error event listener to the image.
  2. If the image doesn't load successfully, change its src attribute.
  3. Optionally, change the image's alt attribute.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <img id="img" src="does-not-exist.png" alt="banner" /> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const img = document.getElementById('img'); img.addEventListener('error', function handleError() { const defaultImage = 'https://bobbyhadz.com/images/blog/javascript-show-div-on-select-option/banner.webp'; img.src = defaultImage; img.alt = 'default'; });

We added an error event listener to the image element.

If the image fails to load, an error event is fired at the element that initiated the load and the onerror() handler on the image is invoked.

If you set the image's src attribute to a non-existent image, it would re-trigger the error event, causing an infinite loop.

Inside of the error handler function, we update the image's src attribute to a default image and change the value of the image's alt attribute.

If you need to show a default image if the original is not found for multiple images:

  1. Select the images using the querySelectorAll() method.
  2. Iterate over the collection using the forEach() method.
  3. Add an error event listener to each image.
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <img src="does-not-exist.png" alt="banner" /> <img src="does-not-exist.png" alt="banner" /> <img src="does-not-exist.png" alt="banner" /> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const images = document.querySelectorAll('img'); images.forEach(img => { img.addEventListener('error', function handleError() { const defaultImage = 'https://bobbyhadz.com/images/blog/javascript-show-div-on-select-option/banner.webp'; img.src = defaultImage; img.alt = 'default'; }); });

We used the querySelectorAll method to select all of the img elements on the page.

The method takes a string containing one or more valid CSS selectors.

The function we passed to the forEach method gets called with each image in the NodeList.

On each iteration, we add the error event listener to the image to provide a backup if the original doesn't load.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee