Last updated: Mar 5, 2024
Reading time·2 min
To show a default image if the original image is not found:
error
event listener to the image.src
attribute.alt
attribute.Here is the HTML for the examples.
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <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.
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 img
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.
src
attribute to a non-existent image, it would re-trigger the error
event, causing an infinite loop.Inside 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:
querySelectorAll()
method.forEach()
method.error
event listener to each image.<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <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.
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 document.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.
You can learn more about the related topics by checking out the following tutorials: