Image Gallery

Based on code by Jeremy Keith.

Simple photo gallery JavaScript. All that is needed is:

The captions can be in several different places:

  1. the title attribute of the anchor tag
  2. if the title attribute is not there then the text from inside the anchor tag is used
  3. if there is an image, the alt attribute is used as long as there is no title attribute on the anchor

Gallery Images

DVD Case Bug Vader Bug Vader (caption from link text itself - no title attribute) Bug Vader (caption from the alt attribute of the thumbnail)DVD Label (not used because the anchor has a value for the title attribute)
Click on a link or thumbnail above to see the image

JavaScript Used

// A simple image gallery. // You'll need a placeholder image with the id "largeGalleryImage". // You'll also need an element with the id "imageCaption" to hold the descriptive text. // Feel free to alter this as you see fit. // All I ask is that you drop me a line to let me know where you use it. // Email me: jeremy at adactio.com // Some modifications to showPic() by Stan Grabowski function showPic (whichpic) { if (document.getElementById) { // write the image into the placeholder area document.getElementById('largeGalleryImage').innerHTML = '<img src="'+ whichpic.href +'" alt="' + whichpic.title + '">'; if (whichpic.title) { // if the anchor has a title, add that info into the imageCaption area document.getElementById('imageCaption').childNodes[0].nodeValue = whichpic.title; } else if (whichpic.childNodes[0].nodeName == "IMG") { // if the first child of the anchor tag is an image tag, then use the alt attribute for the caption. // only works if the anchor has no title element document.getElementById('imageCaption').childNodes[0].nodeValue = whichpic.childNodes[0].getAttribute("alt"); } else { // if the anchor has no title attribute, then just use the text... document.getElementById('imageCaption').childNodes[0].nodeValue = whichpic.childNodes[0].nodeValue; } return false; } else { return true; } } function checkObjects() { // grab all the galleryImages area... var galleryImagesArea = document.getElementById("galleryImages"); // loop through all child elements of galleryImages... for(var i=0;i<galleryImagesArea.childNodes.length;i++) { // find any anchor... if (galleryImagesArea.childNodes[i].nodeName == 'A') { // run the showPic() function when the anchor is clicked. galleryImagesArea.childNodes[i].onclick=function(){return(showPic(this));}; } } } // addLoadEvent() // Adds event to window.onload without overwriting currently assigned onload functions. // Function found at Simon Willison's weblog - http://simon.incutio.com/ function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function(){oldonload();func();}; } } addLoadEvent(checkObjects);