Hide a broken image in HTML when the file is missing

By

Learn how to avoid a broken image in HTML when the file is missing by using the img onerror attribute to remove the element or swap in a fallback image.

~~~

To hide a broken image in HTML, use the onerror attribute of the img tag. When the browser fails to load the image file, it fires an error event on the element, and you can use that to remove the element or swap in a fallback.

Here’s how I got there. While working on a website I was loading an image dynamically based on the current page URL.

Being sure I’d eventually forget to create an image in the future, I looked into avoiding the usual “broken image” icon that says “this website is abandoned”.

Removing the broken image

The technique I used is this:

<img src="/{{$bookname}}.png" onerror="this.remove()" />

TIP: this inside an inline event handler in HTML refers to “this element”

If the file exists, nothing happens and the image displays normally. If the request fails, the browser runs the handler and the element deletes itself from the page. No broken icon, no leftover alt text.

Sure, the optimal way is to make sure images always work. But that’s not realistic from many points of view. This is a workaround that uses the platform features, because I know I might not pay attention to that as I’m a solo developer, and I might have a broken image visible for weeks before I realize.

Showing a fallback image instead

Another thing you could do is display a fallback image, if you need, in this way:

<img
  src="/{{$bookname}}.png"
  onerror="this.onerror=null; this.src='fallback.png'"
/>

There’s a trap hidden in this version. Setting this.src starts a new image request. If fallback.png is also missing, that request fails too, onerror fires again, sets the same src again, and you’re in an infinite loop of failing requests.

That’s why we set this.onerror=null first. The handler removes itself before swapping the source, so it can only run once. If the fallback is broken you’re back to the broken icon, but at least nothing loops.

A couple of things to keep in mind

remove() deletes the element entirely, so the surrounding layout collapses as if the image was never there. If you’d rather keep the space it occupied, set this.style.visibility='hidden' instead. The element stays in the page, invisible, at its normal size.

Also note that this relies on JavaScript running in the page. With JavaScript disabled you get the broken icon anyway. For the “I might forget to create this file” case, that’s a trade-off I’m happy with.

Tagged: HTML · All topics
~~~

Related posts about html: