Skip to main content Accessibility Feedback

Handling missing images with vanilla JS

Today, I want to show you a quick little vanilla JS trick for replacing that default missing image icon your browser shows with a fallback image of your choice.

The secret: the error event and event delegation.

First, let’s setup an event listener on the document for error events.

document.addEventListener('error', function (event) {
	// Do something when there's an error...
}, true);

Next, we want to check if the element that triggered the event is an image. We’ll check the tagName property of the event.target.

document.addEventListener('error', function (event) {
	if (event.target.tagName.toLowerCase() !== 'img') return;
}, true);

Finally, if the element is an image, we can replace it’s src property with our fallback image. We should probably also update the alt attribute.

document.addEventListener('error', function (event) {
	if (event.target.tagName.toLowerCase() !== 'img') return;
	event.target.src = 'https://media.giphy.com/media/JAAot6yVvkHni/giphy.gif';
	event.target.alt = 'The real image is missing! This is a gif of WALL-E sitting on a bench.';
}, true);

Here’s a demo of this trick in action.