Borislav Hadzhiev
Last updated: Jan 6, 2022
Check out my new book
To check if an img src is valid:
error
event listener on the img
element.src
is invalid, set it to a backup image.Here is the HTML for the examples in this article.
<!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.
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.
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.
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.
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.