Checking for missing images
If you are displaying some images in the browser and unfortunately some of the images are missing, the browser will either display a blank space or will display a placeholder with a cross symbol. This surely looks ugly and you would definitely want to avoid it. Wouldn't it be good if you had a method with which you could find missing images or those that failed to load?
After going through this recipe you will be able to detect missing images and replace them with an image of your choice.
Getting ready
Get three or four images from your computer. You will need these with this recipe. Also keep the jQuery file handy. Create another image using a program like paint with text "Could not load image" written on it. This will be the default placeholder for images that fail to load.
How to do it...
Create a new file in the
chapter1
directory and name it aserror.html
.Place a DIV in the page, which will be filled with images. Also, write some CSS to style the DIV and the images.
<html> <head> <title>Check missing images</title> <style type="text/css"> div { border:1px solid black; float:left; } img { width:180px; height:200px; margin:10px; } </style> </head> <body> <div id="imageContainer"></div> </body> </html>
Write the jQuery code that creates an array of image names. Intentionally put some random names of images that do not exist. Then fill the DIV by creating image tags from this array. Next, bind the
error()
event handler to the image elements.<script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function () { var images= ['himalaya.png', 'chaukori.png', 'tree.png', 'noSuchimage.png', 'anotheNonExistentImage.png']; var html = ''; $.each(images,function(key, value) { html+= '<img src="'+value+'" />'; }); $('#imageContainer').html(html); $('img').error(function() { $(this).replaceWith('<img src="missing.png" alt="Could not load image">'); }); }); </script>
Run the
error.html
file in a browser. You will see that the last two images, which do not exist, have been replaced by another image that says Could not load image.
How it works...
First we use jQuery's $.each()
method to iterate in the array that holds image names and fills the DIV by creating image
tags.
Then there is an error()
event handler attached to image
tags. This gets executed when the image fails to load or has a broken src
attribute. The event handler for the error()
method replaces the nonexistent image with another image of our choice. In our case we replace it with an image that we have created and that says Could not load image.
See also
Binding and unbinding elements, which explains the basics of adding events.