Build a stylish image gallery using Lightbox 2 and JavaScript

Create stunning image displays with custom controls using a simple JavaScript library

The Web has increasingly become a medium for showing off art. From candid snapshots taken by an amateur photographer to professional art galleries, Web pages are primary vehicles for displaying images. But a beautiful image is hindered—or aided—by its frame. Using a simple JavaScript library, you can "frame" your online images beautifully and provide an intuitive user interface along the way.

Share:

Brett D. McLaughlin, Sr., Author and Editor, O'Reilly Media, Inc.

Photo of Brett McLaughlinBrett McLaughlin is a best-selling and award-winning non-fiction author. His books on computer programming, home theater, and analysis and design have sold in excess of 100,000 copies. He has been writing, editing, and producing technical books for nearly a decade, and is as comfortable in front of a word processor as he is behind a guitar, chasing his two sons around the house, or laughing at reruns of Arrested Development with his wife. His last book, Head First Object Oriented Analysis and Design, won the 2007 Jolt Technical Book award. His classic Java and XML remains one of the definitive works on using XML technologies in the Java language.



28 October 2008

Also available in Chinese

JavaScript is arguably the most ubiquitous programming language of the Web and is nearly as pervasive as HTML, XHTML, and CSS. There are a wealth of useful JavaScript libraries, too, and the best of these work on any modern browser, handling browser variances and user preferences uniformly. One of the most useful and popular JavaScript libraries is Lightbox 2, which provides online image gallery capabilities, image overlays, and navigation within sets (or groups) of images. In this article, you'll learn the ins and outs of Lightbox 2, including how to customize some of the lesser-known—and at times subtler—capabilities of a Lightbox. By the time you're through, you'll be showing your own image sets off with flair, all within an easily usable interface.

Everyone's a photographer these days

Five years ago, it seemed like everyone was blogging. Mothers, grandmothers, uncles, soldiers, and athletes were all going online to share the latest minutiae from their lives. Lately, the trend has been to display your photos online.

With a few hundred bucks, even high school students can purchase a nice digital camera and begin building their photography skills. But most photos are meant to be shared, not admired only by their taker. That's where the Web comes in: The Web provides a bigger platform than any art gallery (although perhaps with less distinguished tastes). But a beautiful photo slapped into an HTML page amidst some text can quickly lose its appeal. And potential in a novice photographer can be overshadowed by a horrible Web design.

Enter Lightbox (and now its successor, Lightbox 2). Lightbox is a JavaScript library that provides a full-featured image viewer. Images are displayed in a slick "overlay" that sits atop the main Web page. Navigation, image descriptions, and even custom buttons are all a possibility. At its simplest, a lightbox looks something like Figure 1.

Figure 1. The default Lightbox viewer
Even at its simplest, Lightbox provides a nice viewer for images

As you'll soon learn, though, you can take Lightbox a lot further than this utilitarian setting.

Before digging deeper into the specifics, there are a few good reasons to use Lightbox, and you should know each of them. Even if you're personally convinced, you may want to get a coworker, boss, or friend to agree with using Lightbox on a site. Besides, understanding why you choose a particular technology or tool is often as important as the tool itself.

Lightbox is JavaScript

First, Lightbox is JavaScript. With every modern browser (and several very un-modern browsers) supporting JavaScript "out of the box," you can be sure your pages will work easily on most users' browsers. While there are certainly other great plugin-based technologies, like Flash or the Microsoft® suite of controls, JavaScript is part of every browser. So, you don't need your users to download special components or worry about updating their browsers (within reason). Almost every computer user with a browser will be able to view your lightboxes just as you designed them.

Lightbox is browser-neutral

Not only is Lightbox built with JavaScript, it's built with cross-browser JavaScript. In other words, Lightbox will work on any modern browser, and work the same way across those browsers. Internet Explorer, Safari, Firefox, Opera—they'll all handle the Lightbox code in the same way. That means that when you use Lightbox, you're building code and pages that aren't requiring your users to choose a particular browser (or operating system). And that, in turn, means more users, more people seeing your photos, and less irritated calls from your mother-in-law who wants to see your latest photos of the grandkids. That's a good thing, right?

Lightbox builds on existing libraries

Finally, Lightbox actually builds on two well-established JavaScript libraries, Prototype and Scriptaculous. Prototype provides some utility functions for working with a page and its objects, and Scriptaculous adds a ton of display effects. Both are well-tested, have been around for a few years, and are also standard JavaScript, built to work across all modern browsers. The end result is that Lightbox is building on solid code, rather than reinventing the wheel (and introducing its own bugs).


Download and "install" Lightbox

As with any JavaScript library, getting Lightbox set up is quick and painless. Here's exactly what you need to do.

Download Lightbox

Visit the Lightbox Web site (actually, the Lightbox 2 site) by clicking the "Lightbox 2 Web site" link in the Resources section of this article. On the left-side navigation, find and click the "Download" link. Your browser should look something like Figure 2.

Figure 2. The Lightbox download section
Lightbox provides a simple, small download

Clicking the large Lightbox link will get you a ZIP file, named something like lightbox2.04.zip. (The name may change slightly based on the version.) You can expand that into a folder, called lightbox2/. Figure 3 shows the internals of the download folder: pretty simple stuff.

Figure 3. The Lightbox download contents
Lightbox comes with CSS, some scripts, and some images

Make the Lightbox files accessible to your site

What directory do your scripts go in?

The traditional approach to scripting suggests that you put all your scripts into a directory of your site called scripts/. So the path to a script might be scripts/prototype.js. Lately, though, there's been a move to more specificity in script-directory naming. So you would have a js/ directory for JavaScript, and perhaps an asp/ directory for ASP.NET scripts. That's the model that Lightbox uses, and it might require a bit of adjustment if you've used scripts/ in all of your previous sites.

Now you need to make all the Lightbox files—including the images and CSS it uses—available for your Web site. Fortunately, the Lightbox download is already primed for this. It uses standard directory names like images/, css/, and js/. So you can copy those three directories and their contents directly into your Web site's root and probably be ready to go.

One thing you should be cautious about: The default Lightbox download includes an index.html file. You do not want to copy that into your Web root, as you'll almost certainly blow away your own site's index page. That page in the installation is a set of instructions, but you've got this article, so you may just want to delete index.html to avoid confusion.

Reference the three Lightbox-related files

Once you've got the right files in the right places, you can reference those files. Here are the three lines of JavaScript you'll want to add to all your pages in which you intend to use Lightbox:

<script type="text/javascript" src="js/prototype.js"></script>
<script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"></script>
<script type="text/javascript" src="js/lightbox.js"></script>

You'll also need to include a link to the Lightbox CSS stylesheet:

<link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" />

Before we can get into much detail about what each of these scripts and sheets does, you'll need a sample page to work with.


Build a simple example app

To get started, we need a page with some images. Listing 1 shows the HTML for a gallery page. Go ahead and type this HTML into your own editor, or copy and paste it, or download the code from the examples (available in the Resources section).

Listing 1. HTML for example image gallery
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
 <title>Image Gallery</title>

 <link rel="stylesheet" href='css/gallery.css' type="text/css" 
       media="screen, projection" />
</head>


<body>

 <h1>Image Gallery</h1>

 <div id="page">
  <div id="images">

   <ul class="gallery">

    <li><img src="img/photo01.jpg" alt="description" /></li>
    <li><img src="img/photo02.jpg" alt="description" /></li>
    <li><img src="img/photo03.jpg" alt="description" /></li>
    <li><img src="img/photo04.jpg" alt="description" /></li>
    <li><img src="img/photo05.jpg" alt="description" /></li>
    <li><img src="img/photo06.jpg" alt="description" /></li>
    <li><img src="img/photo07.jpg" alt="description" /></li>
    <li><img src="img/photo08.jpg" alt="description" /></li>
    <li><img src="img/photo09.jpg" alt="description" /></li>
    <li><img src="img/photo10.jpg" alt="description" /></li>
    <li><img src="img/photo11.jpg" alt="description" /></li>
    <li><img src="img/photo12.jpg" alt="description" /></li>
    <li><img src="img/photo13.jpg" alt="description" /></li>
    <li><img src="img/photo14.jpg" alt="description" /></li>
    <li><img src="img/photo15.jpg" alt="description" /></li>
    <li><img src="img/photo16.jpg" alt="description" /></li>
    <li><img src="img/photo17.jpg" alt="description" /></li>
    <li><img src="img/photo18.jpg" alt="description" /></li>
    <li><img src="img/photo19.jpg" alt="description" /></li>
    <li><img src="img/photo20.jpg" alt="description" /></li>

  </ul>
 </div>
</div>


</body>

</html>

Listing 2 is the CSS for this example page.

Listing 2. CSS for example image gallery
*

{

	border: 0;

	margin: 0;

	padding: 0;

}



body

{

	background: #fff;

	color: #777;

	padding: 50px;

}

#page {
  position: relative;
}

#images {
  float: left;
  width: 600px;
}

#details {
  color: #000;
}



h1

{

	background: inherit;

	border-bottom: 1px dashed #ccc;

	color: #933;

	font: 32px Georgia, serif;
        font-weight: bold;

	margin: 0 0 20px;

	padding: 0 0 15px;

	text-align: center;

}



.gallery

{
        width: 700px;

	cursor: default;

	list-style: none;

}



.gallery img

{

	background: #fff;

	border-color: #aaa #ccc #ddd #bbb;

	border-style: solid;

	border-width: 1px;

	color: inherit;

	padding: 2px;

	vertical-align: top;

	width: 100px;

	height: 75px;

}



.gallery li

{

	background: #eee;

	border-color: #ddd #bbb #aaa #ccc;

	border-style: solid;

	border-width: 1px;

	color: inherit;

	display: inline;

	float: left;

	margin: 3px;

	padding: 5px;

	position: relative;

}

Be sure you've got the HTML and CSS in place and that you've downloaded the referenced images from the Resources section. Then, load up the HTML you just created. You should see something like Figure 4.

Figure 4. An image gallery in need of a Lightbox
The images in the gallery all bear a closer look

This is a perfect page for a Lightbox: There are lots of images, and the images are high-resolution. They'd be ideal for a larger display, but to show the images at full size within the main HTML would waste a lot of space.


Add Lightbox to the gallery page

With an actual page to work on, you're ready to put those script references mentioned above into place. Then, a few more simple steps, and you're ready to see Lightbox in action on a working site that you created.

Reference the correct scripts

First, open up index.html (or whatever you've called the example gallery page). In the head section, add the lines shown in Listing 3.

Listing 3. References to Lightbox scripts (in context)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
 <title>Image Gallery</title>

 <link rel="stylesheet" href='css/gallery.css' type="text/css" 
       media="screen, projection" />
 <script type="text/javascript" src="js/prototype.js"></script> 
 <script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"></script> 
 <script type="text/javascript" src="js/lightbox.js"></script> 
</head>
<-- Rest of HTML ... -->

These script references must be in this particular order. Each successive script references functions in the previous scripts, so ordering is crucial. If you mix the order, you'll get errors on your page, so take particular note that you reference Prototype, then Scriptaculous, and then Lightbox.

Reference the correct CSS

Next, add in a CSS reference, as shown in Listing 4.

Listing 4. Reference to Lightbox CSS (in context)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
 <title>Image Gallery</title>

 <link rel="stylesheet" href='css/gallery.css' type="text/css" 
       media="screen, projection" />
 <script type="text/javascript" src="js/prototype.js"></script>
 <script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"></script>
 <script type="text/javascript" src="js/lightbox.js"></script>
 <link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" />
</head>
<-- Rest of HTML ... -->

This is an easy step to forget, as Lightbox is essentially a set of scripts. But those scripts display images, and the display of those images is controlled by the Lightbox CSS. So this becomes a pretty important (albeit easily forgotten) step.

As a bonus, you can always update the Lightbox CSS to match your own visual preferences. We'll talk a bit more about this later, but it's important to realize that even with a toolkit like Lightbox, separating content (XHTML) from presentation (CSS) from behavior (JavaScript) offers you a ton of flexibility.

Model View Controller

This style of separating content, presentation, and behavior is known architecturally as Model/View/Controller. This disciplined approach is a best practice which works for Web pages as well as enterprise applications. The value of an MVC architecture is that each element can be maintained and adjusted without endangering the others. Data remains independent of format. Function remains independent of data. The easy customization described later in the article is a direct result of its MVC design.

Copy over the Lightbox files to your example directory

Here's another step that's often overlooked: Make sure you've got the Lightbox scripts and CSS in the same directory as your example image gallery. If you've downloaded the gallery and dropped it onto an existing site, just upload the Lightbox files as well. If you're working locally, just make sure you copy the Lightbox scripts/, css/, and images/ directories alongside your image gallery files.

Add links to each image in your gallery

Lightbox works using a elements. So before you can go any further, you'll want to wrap each image on your page that you want shown in a Lightbox in an a tag. Generally, the target of the link—the value of the href attribute—should be the image itself, often displayed at full size.

Listing 5 shows the HTML for the gallery, updated with a tags.

Listing 5. Add links around each image
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
 <title>Image Gallery</title>

 <link rel="stylesheet" href='css/gallery.css' type="text/css" 
       media="screen, projection" />
 <script type="text/javascript" src="js/prototype.js"></script>
 <script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"></script>
 <script type="text/javascript" src="js/lightbox.js"></script> 
 <link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" />
</head>


<body>

 <h1>Image Gallery</h1>

 <div id="page">
  <div id="images">

   <ul class="gallery">

    <a href="img/photo01.jpg"> 
     <li><img src="img/photo01.jpg" alt="description" /></li> 
    </a> 
    <a href="img/photo02.jpg"> 
     <li><img src="img/photo02.jpg" alt="description" /></li> 
    </a> 
    <a href="img/photo03.jpg"> 
     <li><img src="img/photo03.jpg" alt="description" /></li> 
    </a> 
    <a href="img/photo04.jpg"> 
     <li><img src="img/photo04.jpg" alt="description" /></li> 
    </a> 
    <a href="img/photo05.jpg"> 
     <li><img src="img/photo05.jpg" alt="description" /></li> 
    </a> 
    <a href="img/photo06.jpg"> 
     <li><img src="img/photo06.jpg" alt="description" /></li> 
    </a> 
    <a href="img/photo07.jpg"> 
     <li><img src="img/photo07.jpg" alt="description" /></li> 
    </a> 
    <a href="img/photo08.jpg"> 
     <li><img src="img/photo08.jpg" alt="description" /></li> 
    </a> 
    <a href="img/photo09.jpg"> 
     <li><img src="img/photo09.jpg" alt="description" /></li> 
    </a> 
    <a href="img/photo10.jpg"> 
     <li><img src="img/photo10.jpg" alt="description" /></li> 
    </a> 
    <a href="img/photo11.jpg"> 
     <li><img src="img/photo11.jpg" alt="description" /></li> 
    </a> 
    <a href="img/photo12.jpg"> 
     <li><img src="img/photo12.jpg" alt="description" /></li> 
    </a> 
    <a href="img/photo13.jpg"> 
     <li><img src="img/photo13.jpg" alt="description" /></li> 
    </a> 
    <a href="img/photo14.jpg"> 
     <li><img src="img/photo14.jpg" alt="description" /></li> 
    </a> 
    <a href="img/photo15.jpg"> 
     <li><img src="img/photo15.jpg" alt="description" /></li> 
    </a> 
    <a href="img/photo16.jpg"> 
     <li><img src="img/photo16.jpg" alt="description" /></li> 
    </a> 
    <a href="img/photo17.jpg"> 
     <li><img src="img/photo17.jpg" alt="description" /></li> 
    </a> 
    <a href="img/photo18.jpg"> 
     <li><img src="img/photo18.jpg" alt="description" /></li> 
    </a> 
    <a href="img/photo19.jpg"> 
     <li><img src="img/photo19.jpg" alt="description" /></li> 
    </a> 
    <a href="img/photo20.jpg"> 
     <li><img src="img/photo20.jpg" alt="description" /></li> 
    </a>

  </ul>
 </div>
</div>


</body>

</html>

Connect Lightbox to each image

The last step is a simple one: Each a element needs a new attribute, rel, with a value of "lightbox". Just add that attribute into each link that surrounds an image that you want displayed in a Lightbox. Listing 6 shows this change in place.

Listing 6. Add links around each image
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
 <title>Image Gallery</title>

 <link rel="stylesheet" href='css/gallery.css' type="text/css" 
       media="screen, projection" />
 <script type="text/javascript" src="js/prototype.js"></script>
 <script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"></script>
 <script type="text/javascript" src="js/lightbox.js"></script> 
 <link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" />
</head>


<body>

 <h1>Image Gallery</h1>

 <div id="page">
  <div id="images">

   <ul class="gallery">

    <a href="img/photo01.jpg" rel="lightbox">
     <li><img src="img/photo01.jpg" alt="description" /></li>
    </a>
    <a href="img/photo02.jpg" rel="lightbox">
     <li><img src="img/photo02.jpg" alt="description" /></li>
    </a>
    <a href="img/photo03.jpg" rel="lightbox">
     <li><img src="img/photo03.jpg" alt="description" /></li>
    </a>
    <a href="img/photo04.jpg" rel="lightbox">
     <li><img src="img/photo04.jpg" alt="description" /></li>
    </a>
    <a href="img/photo05.jpg" rel="lightbox">
     <li><img src="img/photo05.jpg" alt="description" /></li>
    </a>
    <a href="img/photo06.jpg" rel="lightbox">
     <li><img src="img/photo06.jpg" alt="description" /></li>
    </a>
    <a href="img/photo07.jpg" rel="lightbox">
     <li><img src="img/photo07.jpg" alt="description" /></li>
    </a>
    <a href="img/photo08.jpg" rel="lightbox">
     <li><img src="img/photo08.jpg" alt="description" /></li>
    </a>
    <a href="img/photo09.jpg" rel="lightbox">
     <li><img src="img/photo09.jpg" alt="description" /></li>
    </a>
    <a href="img/photo10.jpg" rel="lightbox">
     <li><img src="img/photo10.jpg" alt="description" /></li>
    </a>
    <a href="img/photo11.jpg" rel="lightbox">
     <li><img src="img/photo11.jpg" alt="description" /></li>
    </a>
    <a href="img/photo12.jpg" rel="lightbox">
     <li><img src="img/photo12.jpg" alt="description" /></li>
    </a>
    <a href="img/photo13.jpg" rel="lightbox">
     <li><img src="img/photo13.jpg" alt="description" /></li>
    </a>
    <a href="img/photo14.jpg" rel="lightbox">
     <li><img src="img/photo14.jpg" alt="description" /></li>
    </a>
    <a href="img/photo15.jpg" rel="lightbox">
     <li><img src="img/photo15.jpg" alt="description" /></li>
    </a>
    <a href="img/photo16.jpg" rel="lightbox">
     <li><img src="img/photo16.jpg" alt="description" /></li>
    </a>
    <a href="img/photo17.jpg" rel="lightbox">
     <li><img src="img/photo17.jpg" alt="description" /></li>
    </a>
    <a href="img/photo18.jpg" rel="lightbox">
     <li><img src="img/photo18.jpg" alt="description" /></li>
    </a>
    <a href="img/photo19.jpg" rel="lightbox">
     <li><img src="img/photo19.jpg" alt="description" /></li>
    </a>
    <a href="img/photo20.jpg" rel="lightbox">
     <li><img src="img/photo20.jpg" alt="description" /></li>
    </a>

  </ul>
 </div>
</div>


</body>

</html>

Check out Lightbox in action

All that's left is to save the changes to your HTML and load (or reload) the image gallery. Click on any image and you should see a nice animation as the image opens, full size, in a Lightbox. Check out Figure 5 to see what the results look like on Firefox.

Figure 5. Lightbox-enabled image gallery
Each image comes up in a Lightbox

Each image comes up in a nice, high-contrast box. The rest of the page "fades back" and creates a focus on the selected image. And, of course, there's a nice "Close" button to make it clear what users need to do to return to the entire gallery.


Group images into collections

While the initial, "default" Lightbox is pretty cool, there's a lot more Lightbox can do. The most useful is to group a set of your photos into a ... well ... group. Take the example gallery, for instance. To view the next photo, you've got to close the current one, and then click the next one. But that's not very gallery-like. In a real gallery, you'd just browse to the next photo. Fortunately, Lightbox lets you do something very similar.

Set a group for your photos

For photos you want in a group, you just have to add a group name after the rel="lightbox". You add the group name within brackets ([ and ]), all within the quotation marks. So let's put all the images in the example with a set called "gallery". Listing 7 shows the changes you'd need to make.

Listing 7. Group together all the photos on the page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
 <title>Image Gallery</title>

 <link rel="stylesheet" href='css/gallery.css' type="text/css" 
       media="screen, projection" />
 <script type="text/javascript" src="js/prototype.js"></script>
 <script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"></script>
 <script type="text/javascript" src="js/lightbox.js"></script> 
 <link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" />
</head>


<body>

 <h1>Image Gallery</h1>

 <div id="page">
  <div id="images">

   <ul class="gallery">

    <a href="img/photo01.jpg" rel="lightbox[gallery]">
     <li><img src="img/photo01.jpg" alt="description" /></li>
    </a>
    <a href="img/photo02.jpg" rel="lightbox[gallery]">
     <li><img src="img/photo02.jpg" alt="description" /></li>
    </a>
    <a href="img/photo03.jpg" rel="lightbox[gallery]">
     <li><img src="img/photo03.jpg" alt="description" /></li>
    </a>
    <a href="img/photo04.jpg" rel="lightbox[gallery]">
     <li><img src="img/photo04.jpg" alt="description" /></li>
    </a>
    <a href="img/photo05.jpg" rel="lightbox[gallery]">
     <li><img src="img/photo05.jpg" alt="description" /></li>
    </a>
    <a href="img/photo06.jpg" rel="lightbox[gallery]">
     <li><img src="img/photo06.jpg" alt="description" /></li>
    </a>
    <a href="img/photo07.jpg" rel="lightbox[gallery]">
     <li><img src="img/photo07.jpg" alt="description" /></li>
    </a>
    <a href="img/photo08.jpg" rel="lightbox[gallery]">
     <li><img src="img/photo08.jpg" alt="description" /></li>
    </a>
    <a href="img/photo09.jpg" rel="lightbox[gallery]">
     <li><img src="img/photo09.jpg" alt="description" /></li>
    </a>
    <a href="img/photo10.jpg" rel="lightbox[gallery]">
     <li><img src="img/photo10.jpg" alt="description" /></li>
    </a>
    <a href="img/photo11.jpg" rel="lightbox[gallery]">
     <li><img src="img/photo11.jpg" alt="description" /></li>
    </a>
    <a href="img/photo12.jpg" rel="lightbox[gallery]">
     <li><img src="img/photo12.jpg" alt="description" /></li>
    </a>
    <a href="img/photo13.jpg" rel="lightbox[gallery]">
     <li><img src="img/photo13.jpg" alt="description" /></li>
    </a>
    <a href="img/photo14.jpg" rel="lightbox[gallery]">
     <li><img src="img/photo14.jpg" alt="description" /></li>
    </a>
    <a href="img/photo15.jpg" rel="lightbox[gallery]">
     <li><img src="img/photo15.jpg" alt="description" /></li>
    </a>
    <a href="img/photo16.jpg" rel="lightbox[gallery]">
     <li><img src="img/photo16.jpg" alt="description" /></li>
    </a>
    <a href="img/photo17.jpg" rel="lightbox[gallery]">
     <li><img src="img/photo17.jpg" alt="description" /></li>
    </a>
    <a href="img/photo18.jpg" rel="lightbox[gallery]">
     <li><img src="img/photo18.jpg" alt="description" /></li>
    </a>
    <a href="img/photo19.jpg" rel="lightbox[gallery]">
     <li><img src="img/photo19.jpg" alt="description" /></li>
    </a>
    <a href="img/photo20.jpg" rel="lightbox[gallery]">
     <li><img src="img/photo20.jpg" alt="description" /></li>
    </a>

  </ul>
 </div>
</div>


</body>

</html>

View your Lightbox gallery

Reload your gallery page with these changes. Figure 6 shows a photo chosen.

Figure 6. Photo 1 of a 20-set grouping
Images in the same group are tied together

At first glance, not much is different. There are some subtle changes, though. First, you'll see the gallery images are now numbered, the displayed one with "Image 1 of 20."

Now, mouse over the current photo, and you'll see a "NEXT" button show up. If this weren't the first photo in a set, you could also get a "PREV" button. These buttons take you to the next photo in the group, and the previous photo, respectively. Figure 7 shows the NEXT button displayed.

Figure 7. You can move directly forward and backward within a group
The next button appears when you mouse over a photo

Create multiple galleries on a page

You can create as many different galleries or groups on a single page as you want, just by using different group names within the square brackets used after "lightbox" as the value of the rel attribute. So you might have one gallery of water-related images, and another with faces of actual people.

Be careful about abusing—or even just overusing—multiple galleries, though. For you, the photographer (or designer), it might be apparent why certain photos are in one gallery and not another. You may even design your page to highlight those differences. For the average Web user, though, those differences might be vague, if not completely unapparent. In that case, multiple galleries can cause confusion. Why aren't all the photos displayed? Why can I click NEXT on this photo, but not on another?

When in doubt, sticking with a single gallery containing all of a single page's images is intuitive and has the least chance of confusing your users.


Describe your pictures (it's important!)

Another nice feature of Lightbox is its ability to display some extra information about your images. Just as a gallery can add little plaques beneath pictures, you can add titles to your images.

Add title attributes to your "a" elements

You've already surrounded each image with an a element. It's that a element that's actually the primary way of supplying information to Lightbox. You've used it to indicate that an image should be shown in a Lightbox, as well as to indicate the grouping of a photo. Now, you can use the same a element to add titles to your images.

Add a title attribute, and then as the attribute's value, supply an image title. Listing 8 shows this for several images.

Listing 8. Title your images (using the a element)
<div id="page">
  <div id="images">

   <ul class="gallery">

    <a href="img/photo01.jpg" rel="lightbox[gallery]" title="Sunrise over the bay">
     <li><img src="img/photo01.jpg" alt="description" /></li>
    </a>
    <a href="img/photo02.jpg" rel="lightbox[gallery]" title="Birds scattering at dusk">
     <li><img src="img/photo02.jpg" alt="description" /></li>
    </a>
    <a href="img/photo03.jpg" rel="lightbox[gallery]" 
          title="Rock balanced precariously on rock">
     <li><img src="img/photo03.jpg" alt="description" /></li>
    </a>
    <a href="img/photo04.jpg" rel="lightbox[gallery]" 
          title="I saw men as trees walking...">
     <li><img src="img/photo04.jpg" alt="description" /></li>
    </a>
  <-- etc... -->
  </ul>
 </div>
</div>

View your image titles

Now reload your page. Click on an image, and you'll see the image's title, bolded, just above the group information about an image. Figure 8 shows the title of the example gallery's fourth image.

Figure 8. Titles show up in the lightbox
Your titles are on the a element, but displayed by the lightbox

The Lightbox title is additional image information

Keep in mind that the title you add for an image's Lightbox is specific to the Lightbox. In fact, you're not adding a title to the image itself at all; that would require a change to the img element. This leads to a common mistake: The alt attribute of an image has nothing to do with what's displayed in an image's Lightbox. It's arguable whether that's a good or bad thing, but it's certainly a factual thing.

The idea is to make Lightbox as unobtrusive as possible. So if you've given your image an alt description, or even a long description (using longdesc), those attributes don't have to be affected or changed to add a title for use by Lightbox. In fact, you're encouraged to add alt attributes to your images, anyway, as XHTML requires that attribute for every image on a page.


Changing basic Lightbox UI properties

Everything you've seen so far is "standard" Lightbox fare. But there's a lot more available, especially if you're willing to play around a bit with the Lightbox CSS and images.

Change the Lightbox CSS

Remember, all of the display properties for Lightbox are included in the CSS file lightbox.css. Since CSS is just plain text, there's nothing preventing you from opening that file up and changing whatever you like. In fact, as seen in Listing 9, the CSS isn't even that complex.

Listing 9. CSS for Lightbox
#lightbox{	position: absolute;	left: 0; width: 100%; z-index: 100; 
     text-align: center; line-height: 0;}
#lightbox img{ width: auto; height: auto;}
#lightbox a img{ border: none; }

#outerImageContainer{ position: relative; background-color: #fff; 
                      width: 250px; height: 250px; margin: 0 auto; }
#imageContainer{ padding: 10px; }

#loading{ position: absolute; top: 40%; left: 0%; height: 25%; width: 100%; 
          text-align: center; line-height: 0; }
#hoverNav{ position: absolute; top: 0; left: 0; height: 100%; width: 100%; z-index: 10; }
#imageContainer>#hoverNav{ left: 0;}
#hoverNav a{ outline: none;}

#prevLink, #nextLink{ width: 49%; height: 100%; 
           background-image: url(data:image/gif;base64,AAAA); 
           /* Trick IE into showing hover */ display: block; }
#prevLink { left: 0; float: left;}
#nextLink { right: 0; float: right;}
#prevLink:hover, #prevLink:visited:hover { 
     background: url(../images/prevlabel.gif) left 15% no-repeat; }
#nextLink:hover, #nextLink:visited:hover { 
     background: url(../images/nextlabel.gif) right 15% no-repeat; }

#imageDataContainer{ font: 10px Verdana, Helvetica, sans-serif; background-color: #fff; 
                     margin: 0 auto; line-height: 1.4em; overflow: auto; width: 100%; }

#imageData{	padding:0 10px; color: #666; }
#imageData #imageDetails{ width: 70%; float: left; text-align: left; }	
#imageData #caption{ font-weight: bold;	}
#imageData #numberDisplay{ display: block; clear: left; padding-bottom: 1.0em;	}
#imageData #bottomNavClose{ width: 66px; float: right;  
     padding-bottom: 0.7em; outline: none;}	 	

#overlay{ position: absolute; top: 0; left: 0; z-index: 90; width: 100%; 
          height: 500px; background-color: #000; }

Anything represented by one of these CSS properties is fully controllable. So suppose you wanted:

  • A black background for each picture
  • A black background for the details about each image, with white text
  • Times New Roman font in 12 point for the image description
  • A gray fade on the rest of the page, instead of the darker fade currently used

All of those changes are possible. Listing 10 shows an updated version of lightbox.css that addresses all these items.

Listing 10. Updated CSS for Lightbox
#lightbox{	position: absolute;	left: 0; width: 100%; z-index: 100; 
     text-align: center; line-height: 0;}
#lightbox img{ width: auto; height: auto;}
#lightbox a img{ border: none; }

#outerImageContainer{ position: relative; background-color: #000; 
                      width: 250px; height: 250px; margin: 0 auto; }
#imageContainer{ padding: 10px; }

#loading{ position: absolute; top: 40%; left: 0%; height: 25%; width: 100%; 
          text-align: center; line-height: 0; }
#hoverNav{ position: absolute; top: 0; left: 0; height: 100%; width: 100%; z-index: 10; }
#imageContainer>#hoverNav{ left: 0;}
#hoverNav a{ outline: none;}

#prevLink, #nextLink{ width: 49%; height: 100%; 
           background-image: url(data:image/gif;base64,AAAA); 
           /* Trick IE into showing hover */ display: block; }
#prevLink { left: 0; float: left;}
#nextLink { right: 0; float: right;}
#prevLink:hover, #prevLink:visited:hover { 
     background: url(../images/prevlabel.gif) left 15% no-repeat; }
#nextLink:hover, #nextLink:visited:hover { 
     background: url(../images/nextlabel.gif) right 15% no-repeat; }

#imageDataContainer{ font: 12px Times New Roman; background-color: #000; 
                     margin: 0 auto; line-height: 1.4em; overflow: auto; width: 100%; }

#imageData{	padding:0 10px; color: #fff; }
#imageData #imageDetails{ width: 70%; float: left; text-align: left; }	
#imageData #caption{ font-weight: bold;	}
#imageData #numberDisplay{ display: block; clear: left; padding-bottom: 1.0em; }
#imageData #bottomNavClose{ width: 66px; float: right;  
     padding-bottom: 0.7em; outline: none;}

#overlay{ position: absolute; top: 0; left: 0; z-index: 90; width: 100%; 
          height: 500px; background-color: #666; }

Make these changes to your own version of lightbox.css (you may want to save a copy of the original). Then reload your page, click on an image, and you'll see something like Figure 9.

Figure 9. A darker, modified Lightbox
The lightbox looks very different, all because of the CSS

Change the Lightbox images

There is one rather glaring problem with the changes in this Lightbox: The CLOSE button is oddly black-on-white, as are the NEXT and PREV buttons. That's in contrast to the otherwise white-on-black color scheme. Thankfully, though, here's another opportunity for you to customize Lightbox. With a tool like Photoshop, Photoshop Elements, or even the open-source G.I.M.P., you can change buttons to look like whatever you want.

Figure 10 shows a very simple, modified version of the CLOSE button; Figure 11 is the PREV button, and Figure 12 is the NEXT button.

Figure 10. Updated CLOSE button
This button closes a lightbox
Figure 11. Updated PREV button
This button goes to the previous image in a group
Figure 12. Updated NEXT button
This button goes to the next image in a group

You can download these images as part of the completed example package, below in the Download table. The CLOSE button is called closelabel.gif, the PREV button is prevlabel.gif, and the NEXT button is nextlabel.gif. Be sure to keep these names, as they're what the Lightbox JavaScript and CSS are set to look for.

The buttons shown here are pretty simple, but you can get as flashy as you like. (But you should avoid actually flashing the buttons. That's way too close to the dreaded <BLINK /> tag.) Still, once you've got new images, drop them into your Lightbox image directory, overwriting the existing button images.

Now reload your gallery and click on an image. You should get something like Figure 13.

Figure 13. Modified Lightbox with custom buttons
The lightbox now has black-on-white buttons

Of course, you can change anything else you like, as well: images, colors, sizes, the wrap around the image, the position of the lightbox—it's all up to you. And, with a cleanly separated presentation layer via CSS, all these changes require no compilation, and no custom coding.


Conclusion

It's easy to write Lightbox off as just one more Web widget, or a JavaScript library that only does one really simple thing. However, the focus in any Web design work has to be on the user. For a user, Lightbox is an innovative, simple, easy approach to viewing photos. The simple opening animation as the image loads is slick, there's a progress indicator as the image loads, and navigation is both intuitive and unobtrusive. All that adds up to an engaging user experience. And, we all know by now that users will spend hours checking out photos on the Web.

Even better, and particularly important to you, the developer or designer, is the fact that Lightbox is cross-browser. You're not stuck asking a user to download a Flash plugin, and you certainly won't spend hours trying to remember if it's margin or padding that Internet Explorer chokes on. The end-result: better Web pages, better image displays, and happy users.

Finally, the sky's the limit when it comes to Lightbox customization. You can change the color scheme, the framing of an image, and its position. You can use your own custom buttons, or a variation of the default buttons. You can even change the fade on the background screen when the Lightbox shows. Add this to custom groupings and the ability to title images, and you've got a pretty robust tool to add to your Web toolkit.


Downloads

DescriptionNameSize
The initial version of the image galleryexamples-initial.zip284KB
The completed version of the image galleryexamples-final.zip391KB

Resources

Learn

  • For a highly-customized, Lightbox-like experience, you can check out two articles on building a customized, Ajax-powered image viewer: Part 1 and Part 2 are both online at IBM developerWorks.
  • Prototype is one of Lightbox's key underlying APIs. There's a great two-part article on using Prototype to build a cool "Twenty Questions" application: Part 1 and Part 2.

Get products and technologies

  • Download Lightbox 2 at the Lightbox 2 Web site.
  • You can also download Lightbox 2 at an alternate site if you're having trouble with the site above.
  • Head First Ajax (Rebecca Riordan, O'Reilly Media, Inc.) covers Ajax in depth, including numerous client-server techniques for dealing with screen effects and user interactivity.
  • Java and XML, Third Edition (Brett McLaughlin and Justin Edelson, O'Reilly Media, Inc.) covers XML from start to finish, including extensive information on XML, XSL, and a number of related XML specifications.

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Web development on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development
ArticleID=348229
ArticleTitle=Build a stylish image gallery using Lightbox 2 and JavaScript
publish-date=10282008