Check if img src is valid using JavaScript

avatar

Borislav Hadzhiev

Thu Jan 06 20222 min read

banner

Photo by Ana Gabriel

Check if img src is valid using JavaScript #

To check if an img src is valid:

  1. Add an error event listener on the img element.
  2. If the src is invalid, set it to a backup image.
  3. Alternatively, hide the image.

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="https://example.com/does-not-exist.jpg" 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() { console.log(img.src); // ๐Ÿ‘‡๏ธ if set to non-existent image, causes infinite loop // img.src = 'backup.webp'; // ๐Ÿ‘ˆ๏ธ must be a valid image });

We set an error event listener on the image element.

When an image's source fails to load, an error event is fired at the element that initiated the load.

When the error event is fired, the handleError function gets invoked.

You could set the image's src property to a backup image or hide the image.

Note that if you set the image's src property to an invalid image, it will trigger the error event again and cause an infinite loop.

An alternative approach is to hide the image if it fails to load.

index.js
img.addEventListener('error', function handleError() { console.log(img.src); img.style.display = 'none'; });

In this example, we set the image's display property to none, which hides the image.

Alternatively, you can set the image's visibility property to hidden, which would make the image invisible, but still take space on the page.

index.js
const img = document.getElementById('img'); img.addEventListener('error', function handleError() { console.log(img.src); img.style.visibility = 'hidden'; });

When an element's visibility property is set to hidden, it still takes up space on the page, however the element is invisible (not drawn). It still affects the layout on your page as normal.

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