PSD to HTML conversion PSD to HTML conversion PSD2HTML.com with over 300 professionals takes the designs to HTML and beyond

Code Snippet

Home » Code Snippets » jQuery » Better Broken Image Handling

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.

Subscribe to The Thread

  1. Kyle Hayes says:

    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.

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~