info343/labs/5/solution/lightbox-ex4.js

// lightbox-ex4.js
// Sample JavaScript solution code for Lab 5: Lightbox
// (Partial solution through Exercise 4.)
// INFO 343, Autumn 2012
// Morgan Doocy

// List of image filenames and captions to display in the gallery.
var IMAGES = [
   { file: 'http://info343.ischool.uw.edu/labs/5/avocado.jpg',    caption: 'Avocado' },
   { file: 'http://info343.ischool.uw.edu/labs/5/beach.jpg',      caption: 'Beach' },
   { file: 'http://info343.ischool.uw.edu/labs/5/biebs.jpg',      caption: 'Biebs' },
   { file: 'http://info343.ischool.uw.edu/labs/5/bling.jpg',      caption: 'Bling' },
   { file: 'http://info343.ischool.uw.edu/labs/5/cat.jpg',        caption: 'Cat' },
   { file: 'http://info343.ischool.uw.edu/labs/5/dew.jpg',        caption: 'Dew' },
   { file: 'http://info343.ischool.uw.edu/labs/5/fall.jpg',       caption: 'Fall' },
   { file: 'http://info343.ischool.uw.edu/labs/5/freeway.jpg',    caption: 'Freeway' },
   { file: 'http://info343.ischool.uw.edu/labs/5/hongkong.jpg',   caption: 'Hong Kong' },
   { file: 'http://info343.ischool.uw.edu/labs/5/leaves.jpg',     caption: 'Leaves' },
   { file: 'http://info343.ischool.uw.edu/labs/5/reflection.jpg', caption: 'Reflection' },
   { file: 'http://info343.ischool.uw.edu/labs/5/tuners.jpg',     caption: 'Tuners' }
];

// When the page is ready, create and inject images into #gallery.
$(document).ready(function() {
   $.each(IMAGES, function(i, image) {
      // Create the image with appropriate attributes.
      var $img = $('<img>').attr('src', image.file).attr('alt', image.caption);
      
      // Create a link whose href is the image file itself - but attach a click
      // handler to show the lightbox and prevent the browser from visiting the
      // image's URL. <!--[<ins>]-->(Here we introduce an anonymous intermediary function to<!--[</ins>]-->
      <!--[<ins>]-->// pass i from here into the enlarge function.)<!--[</ins>]-->
      var $a = $('<a>').attr('href', image.file).click(<!--[<ins>]-->function(event) { enlarge(event, i); }<!--[</ins>]-->);
      
      // Inject the image into the link, and the link into the gallery.
      $img.appendTo($a);
      $a.appendTo('#gallery');
   });
});

// Show the lightbox, enlarging the ith image in the list.
function enlarge(event, <!--[<ins>]-->index<!--[</ins>]-->) {
   // Prevent the browser from visiting the clicked link.
   event.preventDefault();
   
   <!--[<ins>]-->// Create and inject an image into the lightbox with the source and alt of the<!--[</ins>]-->
   <!--[<ins>]-->// ith image in the list.<!--[</ins>]-->
   $('<img>').attr('src', <!--[<ins>]-->IMAGES[index].file<!--[</ins>]-->)<!--[<ins>]-->.attr('alt', IMAGES[index].caption)<!--[</ins>]-->.appendTo('#container');
   
   // Show the lightbox.
   $('#lightbox').show();
}