Creative Commons License
This work is licensed under a Creative Commons License.

Javascript Photo Gallery

Example 1: Single Page for Images and Thumbnails

Here is the photo gallery described (more or less) on this page: Single Page Photo Gallery Demo

If you haven't already I'll again urge you to see how this gallery functions -- most of the photo galleries here on pizza use the script in the way described on this page. Zinneke Parade (in Brussels) Photos being but one example.

People love numbered steps and people writing instructions love giving steps (albeit as few steps as possible and often rather arbitrary in their numbering). So, here are the steps. I think it requires seven. No, five. Five steps to photo gallery nirvana.

  1. Create your photo and image thumbnail directories
  2. Create your photo gallery "container" page
  3. Add areas on the page where the images and thumbnails will be written
  4. Tell the gallery where pictures are located and their images names
  5. Finish with display scripts that run once the page finishes loading

The complete HTML and JavaScript (combines and cleans-up steps 1-5)

top of page

1. Create Photo and Thumbnail Directories

This sounds silly, but a lot of time gets expended debugging scripts that are working just fine, the culprit oft times being sloppy bookkeeping. Bad bookkeeping of a web site means forgetting where you placed a file. Verily, it is a painful lesson. So decide up-front how you want to organize your photos. I prefer one directory for each photo album and a subdirectory off of that for the thumbnails.

To begin let's create a directory, let's call it "mypartyphotos", this is where the full-sized images will be place.

Next, there needs to be a place where the thumbnails live. I like to do this by making a directory within the full-sized images directory. I also like to clearly name it. Thus I'd make a directory "/mypartyphotos/thumbnails/"

We've just encountered our first major, implicit assumption. It is not only what the gallery assumes but what it requires.

All photos must reside in the same directory. All thumbnails must be in the same directory. Photos and their thumbnails may not be mixed in one directory.

Remember, this just applies to a particular gallery. Each gallery may and probably should have its own set of directories.

Brace yourself for another commandment. Full-sized images and their thumbnails are pairs, they just happen to live in different places like Bill and Hillary Clinton. Sure, they are technically a couple and represent the same things, but you rarely ever see them together.

Part of the image-thumbnail kinship is that they share the same file name. Remember, they reside in different directories so they won't suffer identity confusion. And if you always make the thumbnails directory under the full-size image directory you won't get confused either. And, duh, naming it "thumbnails" should also keep it clear, eh, slick?

For a given image the photo and its thumbnail must have the file name, but reside in different directories.

Now it's just a matter of putting the images in the right places. Oh, by the way, David Leslie insists that if you crop an image in any way it is no longer a thumbnail, but a preview or snapshot. To him and his ilk a thumbnail must be a scaled down version that is otherwise unadulterated. Me? I don't care how you choose to make your thumbs. I like ACDSee because it's faster than batching in Photoshop. Moving along, moving along.

top of page

2. Photo Gallery Container Page (the HTML)

Start with an empty web page. In the header link to the Photo Gallery Javascript. (you did set the page Title, didn't you?)


<script type="text/javascript" src="js/pbtsgallery.js"></script>

We'll create a large block of inline Javascript, but its location is important. If we place it in the head it is possible that it will execute before the DOM is complete -- this may cause errors if the script attempts to modify portions of the page that have not been created yet. That leaves either setting up an OnLoad event or writing the script at the bottom of the page. I've picked up the habit of shoving it between the close body close html tags. This really gets Dreamweaver's panties in a bunch, but it's important that this block of code does not attempt to execute until after all of the page elements have been rendered (the DOM is complete). And a long, long time ago I experience problems with onLoad events and, thus, have been naughtily placing script inbetween the two end tags ever since. You may want to do it as a function executed during the onLoad. Have I belabored this enough?

The script must not be placed where it might execute before the browser has completed building the document tree (DOM).

top of page

3. Define Gallery Areas within the HTML

HTML, a good place to start I'd say. If you're unfamiliar with the "id" attribute of HTML tags, well, here's the two second explanation. ID is a name you may assign to any object, paragraph, table cell, image, or container like span. It must be unique on the web page. That's very important. The JavaScript is going to be yelling instructions to various page elements and if it calls out an ID (name) and more than one element wants to respond, well, there will be confusion and when JavaScript encounters confusion it just gives up, puts on its jacket, and heads home. Sometimes it doesn't go directly home, but stops off for a drink which makes it even later arriving home; home where the missus is waiting and now there's hell to pay. So you can see how really, really important it is that you use each ID only once on each page. OK? Cool.

Oh, even though I'm clearly trying to confuse the two you should not: there is a difference between "name" and "id" attributes. We are making use of the "id" attribute. Ignore "name". Really. It isn't that "id" is supported by more web browsers. It is that one Javascript function, getElementById, is consistently supported across browsers and thier feuding DOMs. Without this function the gallery script can't happen. So "id" it is.

So now, finally, let's get going.

Let's begin by defining an area that will receive the thumbnail grid:

<span id="mythumbs"></span>

Next how about an area for the page indexes. This is where, if there are more thumbnails than fit on a page, the script will write links to the other pages. Just like the search results on Google.

<p>Page: <span id="thumbindex"></span></p>

Lastly, add the image stuff. This is made up of a regular image tag plus areas for the selected image's description and its file info (file name and dimensions).

  <img src="images/spacer.gif" border="0" width="1" height="1"
     id="thephoto">
  <span id="caption"></span>
  <span id="photoinfo"></span>

Our HTML is finished, read on to learn how we inform the script how it should behave.

top of page

4. Tell the Gallery Script About Your Photos

Add Images

Oddly, we'll begin with what is really one of the last steps, adding images. But before tackling all the available settings and other minutia of explaining to the script where everything on your web site lives I thought you'd appreciate how the meat of the code is really quite simple. The following code snippet adds four photos to a gallery.

<script language="javascript" type="text/javascript">

  addImg( "22.jpg", "Me on top of marshmallows", 440,323 );
  addImg( "23.jpg", "Janet throws in the towel", 440,582 );
  addImg( "24.jpg", "Conventions are fun!", 440,323 );
  addImg( "25.jpg", "No idea what this is a picture of", 440,323 );

</script>

You call addImg for each photo in your gallery. You tell it the file's name, describe the content, and tell its dimensions, in pixels (width followed by height). Simple. Now, if your photo gallery images are all, or mostly, the same dimensions then with just a minor change most of this information may be made optional and really the only info required to add a single image is the filename. We do this by setting Default Dimensions for the images.

<script language="javascript" type="text/javascript">

  setDefDims( 320, 240 );

  addImg( "Picture_001.jpg", "Me at base camp" );
  addImg( "Picture_002.jpg", "so much for boiling the water" );
  addImg( "Picture_003.jpg" );
  addImg( "Picture_004.jpg", "" );
  addImg( "Picture_005.jpg", "", 240, 320 );
  addImg( "Picture_006.jpg" );
  addImg( "Picture_007.jpg" );
  addImg( "Picture_008.jpg" );

</script>

Two things to note. One, the description field is not required -- omitting it, as on Picture_003.jpg, will is just the same as including an empty description, as on Picture_004.jpg. Second, if your image is not of the default dimensions, see Picture_005.jpg which is landscape -- not portrait like the others, then you need to include the description, even if blank, and then the actual width and height of the image.

Locate Images and Define Thumbnail Grid's Appearance

As already alluded there is more to it. For one thing you need to explain where the files are and what you wish to see. In fact, let's tell it:

  • the large (full size) photos are in a directory named "mypartyphotos"
  • we've placed the small thumbnails in a subdirectory under "mypartyphotos", we've called this subdirectory "thumbnails"
  • the thumbnails are 125 pixels in their widest dimension
  • we want to see two columns and four rows of thumbnails per page (that totals 8 thumbnails per page)
<script language="javascript" type="text/javascript">

  setImgDir( "/mypartyphotos/" );
  setThumbDir( "/mypartyphotos/thumbnails/" );
  setThumbWidth( 125 );
  setCols( 2 );
  setRows( 4 );

</script>

Later we'll see a way to somewhat cheat these rules, but for now you'd better just accept them as fact.

Here we disclose the name and location of a transparent spacer gif. Here's that:

<script language="javascript" type="text/javascript">

  setSpacer( "/images/spacer.gif" );
  setLoadingImg( "images/loading-image.gif" );
  setWrap( true ); 

</script>

OK, sneaked in two other bits. The loading image is optional, but is one of my favorite features. Use this to set an image that is displayed whilst the next photo is downloading. If you have a decent Internet connection you may never see more than a flash of this image, but I sadly know from recent experience the horrors of dial-up and it was then that i finally included this feature.

setWrap is also optional, and in this case, completely redundant as the default is TRUE. This sets the behavior for when a visitor clicks NEXT while already viewing the last image. If wrapping is enabled (TRUE, and as I said, the default) they proceed back to the very first image. If disabled they get an (annoying) alert that tells them they are already on the last image. I think you can tell what I think of this option, but, hey, you should have the choice.

The last required bit of knowledge is to "glue" the script to your HTML page by passing the Id's for the various "moving parts".

Failing to tell the script the unique ID's for your active areas will prevent the gallery from functioning.
<script language="javascript" type="text/javascript">

  setElementId( "pages", "thumbindex" );
  setElementId( "thumbs", "mythumbs" );
  setElementId( "image", "thephoto" );
  setElementId( "info", "photoinfo" );
  setElementId( "description", "caption" );

</script>

setElementId( "info", "photoinfo" ) is optional. If set the gallery script writes the file name and dimensions of the currently selected image to the designated HTML element.

top of page

5. Display the Gallery

OK, the script knows everything it needs in order to dynamically write out a photo gallery. Now, either in an onLoad function or buried after the close body tag we may safely run the scripts that will rewrite parts of the HTML.

The last thing to do is fire-off the script so it can actually emit the HTML to your (now) fully prepared and described page. We do this with one function call.

<script language="javascript" type="text/javascript">

  writeGallery();

</script>

Dang, this is a lot of work... we did already discuss using Dreamweaver templates, no? OK, the only thing left is, if you choose, to enable the keyboard shortcuts.

<script language="javascript" type="text/javascript">

  enableQuickKeys();

</script>

top of page

Complete HTML and JavaScript

Let's pull it together by showing everything we've done (this is the final result). Now, above some creative naming was employed to make the example appear more "real world". Here, if you've copied all of the files from the downlod, you'll get a working page.

HTML first (this won't be a pretty page, but will work). A table has been added to format the various sections.

<html>
  <head>
    <title>My Ugly Photo Gallery</title>
    <script type="text/javascript" src="pbtsgallery.js"></script>
  </head>
<body>
<table border="1">
  <tr>
    <td>
      <img src="images/spacer.gif" border="1" width="1" height="1"
       id="thephoto">
      <br><span id="caption"></span>
      <br><span id="photoinfo"></span>
      </td>
    <td>
      <p>Page: <span id="thumbindex"></span></p>
      <span id="mythumbs"></span>
      </td>
    </tr>
</table>

<!-- this is where we'll insert the JavaScript -->

</body>
</html>

Now the script that will initialize the gallery; set directories, describe images, and finally emit the HTML.

<script language="javascript" type="text/javascript">

  setDefDims( 320, 240 );

  addImg( "1.gif", "Me at base camp" );
  addImg( "2.gif", "so much for boiling the water" );
  addImg( "3.gif" );
  addImg( "4.gif", "" );
  addImg( "5.gif", "", 300, 150 );
  addImg( "6.gif" );
  addImg( "7.gif" );
  addImg( "8.gif" );
  addImg( "9.gif" );
  addImg( "10.gif" );
  addImg( "11.gif" );
  addImg( "12.gif" );

  setImgDir( "images/photos/" );
  setThumbDir( "images/photos/thumbs/" );

  setThumbWidth( 125 );
  setCols( 2 );
  setRows( 4 );

  setSpacer( "images/shim.gif" );
  setLoadingImg( "images/loading-image.gif" );

  setWrap( true ); 

  setElementId( "pages", "thumbindex" );
  setElementId( "thumbs", "mythumbs" );
  setElementId( "image", "thephoto" );
  setElementId( "info", "photoinfo" );
  setElementId( "description", "caption" );

  writeGallery();

  enableQuickKeys();

</script>

See the above page in action here.

top of page

 

Script from PizzaByTheSlice.com. Visit the Javascript tips for instructions and latest version.