Displaying A Default Image


Have you ever wanted to display a default image if the img tag source references a file that cannot be found? You might think that you could use the onerror event on the img tag, but don’t be fooled into thinking it’s that easy! No, it isn’t, because most browsers don’t support that event in the way you expect.

Here’s a little bit of JavaScript that I have used to successfully replace a broken image with a default (assumes prototype is used). Also note that this has been extracted somewhat from my implementation and thus may have gathered bugs during the extraction, but the concept should still be clear.

$$('img.my_class_name').each(function(e) {
  var i = new Image();
  i.onerror = function() {
    e.src = "error.png";
    e.onerror = "";
    return true;
  };
  i.src = e.src;
});
  1. #1 by David on April 8, 2009 - 5:19 am

    Great tip – thanks.

(will not be published)