Web Developer Class: How To Use the JavaScript Lightbox Image Viewer

By Scott Clark

You've probably seen the Lightbox JavaScript effect in action on many sites. It overlays a larger version of an image on top of the current page when the smaller image is clicked, and this tutorial for web developers will show you how you can use it on your pages!

First, here is an example of how the Lightbox works:

The Lightbox JS script was written by Lokesh Dhakar, and he has made it available for download and use under the Creative Commons Attribution 2.5 License so you can do anything you want with it as long as you leave his name and link within the script.

To use the Lightbox on your own pages, you'll need to add the external stylesheet and JavaScript code within the HEAD of your document, like this.

<link rel="stylesheet" href="lightbox.css" type="text/css" media="screen" />
<script type="text/javascript" src="lightbox.js"></script>
Now you need to add the code for your thumbnail images. You can do it three ways, as shown above. Here is the code for each method:
<a href="baby_full_belly.jpg" rel="lightbox" ><img src="baby_full_belly_thumb.jpg" /></a>

<a href="punk_the_burmese.jpg" rel="lightbox" title="Baby the Albino Burmese Python"><img src="punk_the_burmese_thumb.jpg" /></a>

<a href="goliath_and_me.jpg" rel="lightbox" title="Me and a Huge Snake" /></a>
The code for the thumbnails is the same as you'd normally see, with the exception of the "rel=lightbox" attribute. The "title" attribute shows a caption, if it is used. You can see it if you mouse over the second image and the text link. Lokesh' script is pretty slick, as it enables you to use thumbnail images and text links, which is very handy.

If you've downloaded the script, you can check out the files it contains which are needed for the script to work. Once you've unzipped it, you'll need to upload them to your web server, and of course, be sure to change any paths within the script and/or CSS files to reflect any differences on your own server (i.e. where you have located the images, etc.).

The two configurable variables are located within the lightbox.js file, and look like this:

var loadingImage = 'loading.gif'; //path to the "loading animation" image
var closeButton = 'close.gif'; //path to the "close" button image
As you can see, adding the Lightbox effect to your pages is not difficult, and makes the display of images so much more professional. Have fun, and see you on the web!

Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
Thanks for your registration, follow us on our social networks to keep up-to-date