Skip to the content...

Welcome to the David Walsh Blog. I'm a MooTools, Dojo, jQuery, CSS, and PHP Web Developer located in Madison, Wisconsin, United States. Please contact me if I can make your experience on my website better.

Remove Broken Images Using MooTools or jQuery

9 Responses »

A while back I wrote a post called Send Email Notifications for Broken Images Using MooTools AJAX. Looking back on that post, I failed to address the image itself. After some thought I've decided it would be best to remove the broken image from the page all together. Below you'll find how to do so using MooTools or jQuery.

The MooTools JavaScript

$$('img').addEvent('error',function() {
	this.dispose();
});

The MooTools way of removing elements from the page is Element.dispose().

The jQuery JavaScript

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

The jQuery way of removing elements from the page is jQuery.remove().

Removing a broken image is a great way of preventing the user from seeing a shortcoming in your website.

Discussion

  1. September 10, 2009 @ 9:26 am

    This trick does not seem to work on IE7, at least not for me.

  2. mr.x.
    September 10, 2009 @ 9:42 am

    I love it! Thanks!

  3. September 10, 2009 @ 10:59 am

    Neat simple trick. The only thing i would argue, and this really comes down to everyones individual situation, is that instead of removing the image, I would replace it with a default/error image.

  4. September 10, 2009 @ 11:17 am

    Looking for this – thank you

    nunage.com

    is ALL broken image. You will notice it on the first page.
    .

  5. September 10, 2009 @ 1:21 pm

    To avoid broken images in wordpress I suggest using the Hot Linked Image Cacher plugin which will cache all hotlinked images in your uploads folder and relink the images to the original source. I run this every couple of posts to keep from having broken images in the first place.

  6. September 10, 2009 @ 1:27 pm

    @Anton: Funny you should mention that:

    MooTools – http://davidwalsh.name/custom-missing-image
    jQuery – http://davidwalsh.name/custom-missing-image-jquery

  7. September 10, 2009 @ 2:49 pm

    jeah – nice, i like the custom-image thing better but thats fine too.

  8. December 10, 2009 @ 1:53 pm

    but maybe with a big rich DOM this could be stressing for the browser (especially shitty ones like IEs)?

  9. March 4, 2010 @ 11:17 am

    @David Walsh: I really like this :)
    Instead of remove it , i’ll replace it with a default / error images :)

Be Heard!

Share your thoughts with fellow developers of all skill levels! I want to hear from you!

Name*:
Email*:
Website:  
Wrap your code with <code> tags, f00!