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

// lightbox-ex3.js
// Sample JavaScript solution code for Lab 5: Lightbox
// (Partial solution through Exercise 3.)
// 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);
      
<!--[<ins>]-->      // 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.
      var $a = $('<a>').attr('href', image.file).click(enlarge);
      
      // Inject the image into the link, and the link into the gallery.
      $img.appendTo($a);
      $a.appendTo('#gallery');<!--[</ins>]-->
   });
});

<!--[<ins>]-->// Show the lightbox, enlarging the ith image in the list.
function enlarge(event) {
   // Prevent the browser from visiting the clicked link.
   event.preventDefault();
   
   // Create and inject an image into the lightbox whose source is the same URL
   // as the clicked link.
   $('<img>').attr('src', $(this).attr('href')).appendTo('#container');
   
   // Show the lightbox.
   $('#lightbox').show();
}<!--[</ins>]-->