Fix Broken Images with jQuery

Use jQuery's error event to do something if an image does not load correctly.

HTML

<img src="http://bestuff.com/images/images_of_stuff/64x64crop/dexters-laboratory-37320.jpg?1173014307" width="64" height="64" />

<!-- This image has a broken URL that returns a 404 page -->
<img src="hhttp://www.google.com/linktoa404page" width="64" height="64" />

<img src="http://bestuff.com/images/images_of_stuff/64x64crop/dexters-laboratory-37320.jpg?1173014307" width="64" height="64" />

CSS

img {
    margin: 1em;
}

JavaScript

var bi = "https://img.youtube.com/vi/D02C5EkBKpE/hqdefault.jpg";

$(bi).bind('error', function(e) {
    var $this = $(this);
    
    // Reset image's src to point to a default image
    // This particular example uses a placeholder image generator to fetch a default with the image's height and width
    $("img").attr('src', 'https://img.youtube.com/vi/D02C5EkBKpE/hqdefault.jpg');
    
    // You could also hide it
    // $(this).hide();
});