Handle Image Loading Errors With jQuery


If an image can't load correctly in the browser it will do a number of things depending on what browser you are using. It will either display a ? question mark image or will just display nothing.

When an image can't be found the browser will throw an error, these errors can be found and used by using jQuery.

You can add an event handler to your images to see if there is an error, if they return an error you can make jQuery do something. For example if an image can't be found you could change the image to a missing image picture, or just hide the image box which is easy to do in jQuery. Here is a small snippet that will either hide the jQuery box or change the image to something else.

// Hide the image on error

// Change the image to a missing image
        $(this).attr('src', 'no-image.jpg');

IE8 And Lower Bug

The above technique won't work with IE8 or lover because of timing issues so you need to add the following lines in the document.ready function.

     $(this).attr('src', $(this).attr('src'));

This is set the image source to itself on the page load which will then start the error event. But this is will slow the page loading time so you want to make sure you only do this for IE8 or lower.

if ( $.browser.msie && $.browser.version < 9 ) { $('img').each(function(){ $(this).attr('src', $(this).attr('src')); }); } [/javascript]

Back to top ^

Join Paulund

  • Get access to 100s of premium tutorials and downloadable content
  • Members content consists of Premium WordPress plugins, CSS packages, jQuery packages, tutorial demo files and templates for 100s of web development tutorials
  • In-depth development tutorials
  • Priority tutorial requests
  • Priority email development support
  • No ads

Here at Paulund you'll find Web Development tutorials and snippets focusing mainly on PHP, WordPress and CSS. Members will get access to premium tutorials that go into more detail about development with these languages. You will also get access to downloadable premium content based on the tutorial.

Join Paulund

Leave a Reply

Your email address will not be published. Required fields are marked *