Automatically Remove Broken Images from the DOM using jQuery

A while back I was tasked with finding a way to automatically remove broken images from a gallery of images. The problem was that, in this system, users were able to bulk-upload image descriptions via CSV and then upload the images later on. If the image gallery went live before all the images were uploaded, the result was a gallery full of broken images that really made the user experience suck (see below for an example demo of the problem).

broken images

At the time, the only way to fix this issue was time-consuming and overly complicated:

  1. User notices that their gallery contains broken images and notifies the developers.
  2. the developers either a) go hunting around for the broken images and upload them or b) run SQL commands to remove the invalid image references from the database.

As you can see, there’s a lot of time and manual labor that goes into fixing this kind of problem. However, there is a way to get around this.

Introducing (and Handling) The Error Event

Images have an error event that fires whenever the image fails to load. With this in mind, you can add an event handler to that event that removes the image if it fails to load. Here’s how to do it using jQuery:

img.error(function() {
    $(this).remove();
});

All this is doing is removing the image from the DOM whenever the image’s error event fires.

Dealing With Multiple Containers

As an additional example, let’s say your image gallery had a link and a div wrapped around it:

<div>
    <a href="http://www.google.com">
        <img alt="" src="myBrokeImage.jpg" />
    </a>
</div>

In that case, you would alter the event handler like so:

img.error(function() {
    $(this).parent().parent().remove();
});

This would remove the entire <div> and not just the image.

Other Cool Things You Could Do With This

There’s some pretty cool things you can do with this event handler beyond just removing the image from the page. You could also:

  1. Send an AJAX request that triggers an email to someone if an image fails to load multiple times.

  2. Retrieve an alternate image or custom placeholder image.

If you need to grab the source of the image that failed, you can simply call

$(this).attr('src')

before you remove the image from the DOM and it will return the path of the image that tried to load.

Things to Keep in Mind

When working with an image’s error event, there are a few things you’ll want to keep in mind:

First, the error event fires after the src attribute of the image has been set. You’ll want to make sure you bind your event handler before this happens by placing the event binding inside of the callback for jQuery’s .ready() method.

Second, if you have a jQuery plugin that expects the images to be present before it is instantiated, make sure you move the instantiation logic into a method that will fire after all elements of the page are done loading such as a handler for the window’s load event.