jQuery/JavaScript to replace broken images

  1. Home
  2. javascript
  3. 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.

First answer

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

Second answer

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

Third answer

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';
    }
  });
});
Reprint:https://stackoverflow.com/questions/92720/jquery-javascript-to-replace-broken-images
Spread the love

Related articles

Comments are closed.