Using jQuery to tidy up missing Images

I’m working on a page that pulls photo’s from a file share on a server by the format of “firstname-lastname-dept.png”. Now 9 times out of 10 this works fine but on the odd occasion an image doesn’t exist.  Now I could do it via c# in code behind to check it exists or I could do it via jQuery.  For this post I am going to do it with jQuery as we could really build upon this post quite easily.

Before we capture the missing Images

I’ve created a simple page with BootStrap and get the following:

Photo Viewer jQuery Image Loaded Not Found

As you can see 2 of the images aren’t found and the alt tag is displayed. This can easily be avoided by adding a couple lines of jQuery magic.

Source/Demo – http://dev.siphilp.co.uk/jQuery-Check-Image-Error.htm

Adding in the jQuery capture

For this we’re going to be using the function “error”.

The error event is sent to elements, such as images, that are referenced by a document and loaded by the browser. It is called if the element was not loaded correctly. * find here - http://api.jquery.com/error/

A very simple implementation is as follows:

[code lang="js"]
$(function () {
if ($.browser.msie) {
$('img').each(function () {
if (this.readyState == 'uninitialized') {
$(this).attr('src', 'images/not-found-image.jpg');
}
});
}
$('img').error(function () {
$(this).attr('alt', 'image not found').attr('src', 'images/not-found-image.jpg');
});
});[/code]

Internet Explorer doesn’t like the Error function so I added a check (line 3-7). After the DOM has loaded it goes through each of the images on the page and checks the readyState. Any images not loaded will be replaced with the not-found-image.

With the above in place we get a nicer look and feel to the page with further options available should we wish to take this little project further.

Photo Viewer jQuery Image Loaded Replaced

I have had a couple of ideas in which I am going to expand on this, I’ll be posting these shortly.

If you want to see the complete source and demo – http://dev.siphilp.co.uk/jQuery-Check-Image-Loaded.htm

  2Comments

  1. Pingback: Using jQuery to tidy up missing Images Part 2 | Simon Philp

  2. Pingback: Using jQuery to tidy up missing Images Part 3 | Simon Philp

Leave a Reply

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

CAPTCHA Image

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>