jQuery/JavaScript to replace broken images

I have a web page that includes a bunch of images. Sometimes the image isn't available, so a broken image is displayed in the client's browser.

How do I use jQuery to get the set of images, filter it to broken images then replace the src?


--I thought it would be easier to do this with jQuery, but it turned out much easier to just use a pure JavaScript solution, that is, the one provided by Prestaul.


Handle the onError event for the image to reassign its source using JavaScript:

function imgError(image) {
    image.onerror = "";
    image.src = "/images/noimage.gif";
    return true;
}
<img src="image.png" onerror="imgError(this);"/>

Or without a JavaScript function:

<img src="image.png" onError="this.onerror=null;this.src='/images/noimage.gif';" />

The following compatibility table lists the browsers that support the error facility:

http://www.quirksmode.org/dom/events/error.html


I use the built in error handler:

$("img").error(function () {
    $(this).unbind("error").attr("src", "broken.gif");
});

Edit: The error() method is deprecated in jquery 1.8 and higher. Instead, you should use .on("error") instead:

$("img").on("error", function () {
    $(this).attr("src", "broken.gif");
});

In case someone like me, tries to attach the error event to a dynamic HTML img tag, I'd like to point out that, there is a catch:

Apparently img error events don't bubble in most browsers, contrary to what the standard says.

So, something like the following will not work:

$(document).on('error', 'img', function () { ... })

Hope this will be helpful to someone else. I wish I had seen this here in this thread. But, I didn't. So, I am adding it


Here is a standalone solution:

$(window).load(function() {
  $('img').each(function() {
    if ( !this.complete
    ||   typeof this.naturalWidth == "undefined"
    ||   this.naturalWidth == 0                  ) {
      // image was broken, replace with your new image
      this.src = 'http://www.tranism.com/weblog/images/broken_ipod.gif';
    }
  });
});