July 8, 2008
An Unobtrusive Image Viewer using jQuery
Continuing from my last presentation on jQuery basics, I thought I would take what I have covered so far and create a little useful example.
This jQuery Image Viewer can be considered and updated to the DOM Image Gallery I discussed last season from Jeremy Keith's DOM Scripting book.
jQuery methods are used to display the hovering image labels shown underneath each thumbnail as well as display the full-size image. A background grey layer is also displayed to "disable" the other thumbnails until a "close" button is clicked. This image viewer is a little more stylish and more in tune to what you see today in other examples on the web.
And if JavaScript is disabled or not available in the browser, the image(s) will still be displayed (on a new page), so the script still retains its core functionality and stays "unobtrusive", which really is important.
This jQuery example is explained in detail in my online class JavaScript: Unobtrusive Programming (Week 5).
The hover effect is created by having a "p" element initally hidden and then have it display "slowly" using the fadeIn("slow") method bound to the mouseover event of the image.

$("img[id!='']").mouseover(function() { // goes to "a" then to sibling "p" to keep it unobtrusive $(this).parent().next().fadeIn("slow"); });
Displaying the image within a "disabled" layer is created by appending a couple elements with the appendTo method.

$("img[id!='']").click(function() { var fullpath = "images/full/" + $(this).attr("id"); $("div").attr("id", "greyout").appendTo(".content"); $("div").attr("id", "fulldiv").appendTo("body"); $("img").attr("src", fullpath).appendTo("#fulldiv"); $("div").attr("id", "closediv").appendTo("#fulldiv"); return false; });
Take a look at the code (.zip) to understand it better.
Further updates to the code would probably include adding an image preloader function to make sure the full-size images display as quickly as possible.
Here is a nice simple one you can use:
function preLoad() { var args = preLoad.arguments; document.imageArray = new Array(args.length); for (var i=0; i < args.length; i++) { document.imageArray[i] = new Image; document.imageArray[i].src = args[i]; } }
You would call this function with the images you want to preload, it'll create a new array with all the images in it, loading them one after another:
preLoad('images/image1.jpg', 'images/image2.jpg');
