Grow your CSS skills. Land your dream job.

Last updated on:

Better Broken Image Handling

Missing images will either just display nothing, or display a [ ? ] style box when their source cannot be found. Instead you may want to replace that with a "missing image" graphic that you are sure exists so there is better visual feedback that something is wrong. Or, you might want to hide it entirely. This is possible, because images that a browser can't find fire off an "error" JavaScript event we can watch for.

// Replace source
$('img').error(function(){
        $(this).attr('src', 'missing.png');
});

// Or, hide them
$("img").error(function(){
        $(this).hide();
});

Additionally, you may wish to trigger some kind of Ajax action to send an email to a site admin when this occurs.

Comments

  1. While this is neat and I didn’t know that imgs threw an error if they can’t be loaded, the usefulness of such a block seems low and somewhat heavy (attaching an event-listener to every img on a page) for something that shouldn’t occur very often.

    I could see this being useful in a case where UGC is being created and the user uploads an image, you could try to display the image if its been processed by the server and if not show a placeholder.

  2. Chandru
    Permalink to comment#

    Hi,
    This is chandru from Chennai(india)…
    You hava a amazing site Every works is useful for me,
    keep it up dude…

  3. Jonathan
    Permalink to comment#

    I really want to implement this on my site, but some of the images are rendered via a PHP script, and this bit of code hides those images for some reason. Can anyone help me out? I don’t like that ugly little icon showing up. I have a image sitting behind where the rendered image should be in case it cannot render it because it is trying to pull down a Minecraft skin and if a user did not upload one the default is not rendered.

    • Jonathan
      Permalink to comment#

      Oops, never mind. Works now. Just played around a bit and got it.

  4. Paul

    Saddly, this does not work in IE – even through IE 9.

  5. Great!! solved my error :)

  6. no it did not on the second glance :((
    I am getting missing image icons on my menu hover how can i deal with it??

    • Esger Jellema
      Permalink to comment#

      It doesn’t work for background images.
      You’ll have to add some to the script if this is your case.

  7. in chrome (forgot to mention)

  8. Arup Panda
    Permalink to comment#

    Hi !!!!
    I dont your name ….
    But this site is very helpful for me ….
    if you put “try yourself” for your code , it is better for user

  9. William
    Permalink to comment#

    Hi all, i cant seem to get this to work. What should the code look like and do i place it before the head or the cose of the body

  10. nash
    Permalink to comment#

    I was doing something similar to this, but then I found this is a bad choice.

    Broken images are not always caused by invalid url or file-not-exist, it could be caused by temporary network problem or slow connection.

    By changing image src of a broken image, users won’t get a chance to see what the real scr is (right click – view image info). It’s even worse to hide the broken image because it’s totally invisible.

    So my solution is to leave the browser broken image alone, and add a reload-image click event to the image.

    For some browsers, you might need to specify dimensions and a border .broken-image {width: 16px !important; height: 16px !important; border: 1px solid #aaa;}, otherwise the image will be invisible. And remove the class on image load.

  11. I don’t have any idea where to paste this code,

    Can you please show me more detail?

  12. Sakknekedro

    $(document).ready(function() {
    $(“img”).error(function() {
    $(this).hide();
    });
    });

    …and then it waits for the site to load entirely and hides imgs afterwards.

    Might cause flickering but surely hides all that needs to be hidden.

  13. Sakknekedro

    Alright, why doesn’t it render markdown codeblocks?

  14. Permalink to comment#

    This was just was I didn’t know I needed! I did how ever change a bit of it…. This way the original source would still be visible and right-click should work.

    JS:

    $(document).ready(function () {
        $('img').error(function () {
            $(this).addClass('noImg');
        });
    });
    

    CSS:


    noImg {
    position: relative;
    border: 1px solid lightgrey;
    background-image: url(http://sirsyedcollege.org/wp-content/themes/EducationAcademy/images/no-image_980x516.jpg);
    background-position: 50% 50%;
    background-repeat: no-repeat;
    -moz-background-size: contain;
    -o-background-size: contain;
    -webkit-background-size: contain;
    background-size: contain;
    height: 75px;
    width: 126px;
    content: "";
    margin: 0 10px 10px 0;
    }

    shorthand

    .noImg {
    position: relative;
    border: 1px solid lightgrey;
    background: url(http://sirsyedcollege.org/wp-content/themes/EducationAcademy/images/no-image_980x516.jpg) 50% 50%/contain no-repeat;
    height: 75px;
    width: 126px;
    content: "";
    margin: 0 10px 10px 0;}

    PS!
    Image credit where image is stolen from, please replace with your own :)

    • Permalink to comment#

      Forgot to give credit to Sakknekedro

    • Permalink to comment#

      In Safari 6.0.5, if you don’t use a background image but just a background color,width and height don’t have any effect if using content: "". Since content: "" is the key factor here to hide both the ? icon and the inner white outline, this works if you just want a custom sized background placeholder:

      .broken-image {
          display: block;
          width: 100%;
          height: 50px;
          content: "";
      }
      
      .broken-image::after {
          display: block;
          text-align: center;
          content: "Broken Image";
      }
      

      I went crazy trying to disable this white outline on a broken image, when my Last.fm script didn’t find an album cover so, glad I found this post.

  15. drooh
    Permalink to comment#

    I believe error is deprecated? Wont work in jQuery above 1.8?

  16. These days (as of jQuery 1.7 I think) you’d want to do something like:

    jQuery( document ).on( 'error', 'img', function( e ){
        $( this ).addClass( 'missing-image' ).attr( 'src', 'url/to/missing.png' );
    });
    

    Doing this will attach one event listener to the document for img child elements, as opposed to the original way which attached a listener to every image element.

  17. Funny solution to all AngularJS users..

    WidgetApp.directive(‘img’, function(){
    return {
    restrict:’E’,
    link:function(scope,element){
    element.error(function(){
    $(this).hide();
    })
    }
    }
    });

    • Sorry about that – clicked “send” before I checked it redners ok.

      WidgetApp.directive('img', function(){
          return {
              restrict:'E',
              link:function(scope,element){
                  element.error(function(){
                      $(this).hide();
                  })
              }
          }
      });
      
  18. Permalink to comment#

    Nice little fix. But how do you prevent the flickering?

    I’m using it to show a default image for a user if they have not uploaded one (no image data in their image location).

  19. Marcellus
    Permalink to comment#

    This worked for me, thanks! But I also had to put this code on the image to work:

    ``<img src=" " onerror="this.style.borderWidth=0" class=" " />``
    

Leave a Comment

Current day month ye@r *

*May or may not contain any actual "CSS" or "Tricks".