JavaScript Image Gallery

by Jeremy Keith

87 Reader Comments

Back to the Article
  1. Just saw this article, and loved the js powered image library idea. I set up a little gallery as a test, and would have to say tha I’m quite impressed.

    Expanding on the idea I added in some css and dhtml styling, and came up with a quick and easy to use multi-page image gallery.

    Unfortunatly due to the IE whitespace bug I had to stick all the thumbnails on 1 line to prevent the floated thumbnails from doing wierd things. I’ve tested this out in IE/mozilla for windows and Safari for mac and things seem to work great. The styles are never seen by NS4 so they get the content without all the design.

    I think i’ll take this idea a little further even and write a small application to auto generate the html files for me.

    Thanks again!

    Feel free to check what i’ve done at:

    Copy & paste the code below to embed this comment.
  2. I just got a job to do a photographers site, good timing ALA.

    To: APA,
    I bow before you. :/

    Copy & paste the code below to embed this comment.
  3. Dasme, your image gallery looks great!

    Using DHTML to show and hide the different pages is a stroke of genius. You’ve managed to pack a heck of a lot of information into one page and yet because the user chooses which portions they want to view, it isn’t at all overwhelming.

    JavaScript + CSS + good information architecture = very cool indeed.

    The idea of an application to create the pages automatically sounds really exciting.

    Copy & paste the code below to embed this comment.
  4. I realize this may sound idiotic to some of you advanced folks out there, but I’m a novice scripter so this is baffling me:

    I wanted to see if I can replicate this script’s effect as-is. Here is the current page with all the photos:

    Instead of all those images. You can see why I’d like to use this technique on that page. Anyway, I wrote the script as described, altered the markup, but for some reason it doesn’t work and I can’t figure out why. A live test is available, though not public, at

    View source to see what I did, and maybe you can set me off in the right direction again. Advance thanks and brownie points to all those who offer help.

    Oh, and…can anyone offer some resources or documentation of what these “nodes” are? I didn’t understand that much…

    Thanks again!

    Copy & paste the code below to embed this comment.
    I’d expect anyone with no computer knowledge at all to know what a node is.

    Copy & paste the code below to embed this comment.
  6. Dude, Dante. Honestly. You have a page.

    I mean, let’s just think about this: geocities.

    I posted my very first pit-cher on a geocities homepage and stuff.

    You’re crackin’ me up, man.

    Copy & paste the code below to embed this comment.
  7. Okay, I appreciate the resource Danté.  :)  (No, seriously I do. I’ll just pretend that was the whole post.)

    Anyway, I did a bunch of trial-and-error runs on this Image Gallery script and noticed the following:

    it all works fine—UNTIL I nest the the second if statement to test for a title attribute. For some reason, using nodes and/or testing for this title attribute sends my javascript awry. And by awry I mean: will always return TRUE and jump me off to follow the link. I can’t seem to reference the desc paragraph.

    Here is the page with a bunch of alerts intended to show where the execution of the script is:

    By the way, if this is an inappropriate forum for this particular kind of discussion, I’d appreciate it if someone just let me know where I should be asking about this.

    Thanks again!

    Copy & paste the code below to embed this comment.
  8. 1. You can use my DOM API I posted here earlier to solve document.getElementById and other DOM problems.
    2. Instead of childNodes0.nodeValue, use .innerText or [removed]. It’s easier and faster.
    3. Main problem: you have an else statement INSIDE and IF statement. Fix that.
    4. I have a geocities page. Yeah. We’re not all rich. I can’t really afford my own server. I’m saving up for a guitar amp. I AM only 14.

    Copy & paste the code below to embed this comment.
  9. Dante,

    thank you again for your advice. I’m familiar with innerHTML and innerText, and thanks to your resource at, now I know what nodes are.

    However, I don’t understand what you mean by my main problem being an else statement inside an if statement.

    I tried to use the exact same JavaScript, character-by-character, that was written in this article (which, DOES work in the same browser I’m trying to use), and this script in this article has an else statement inside an if statement.

    Why is this a problem on my pages but not here on ALA’s article?

    I’ll keep tinkering. :
    Thanks again to anyone who can help.

    Copy & paste the code below to embed this comment.
  10. What I meant was you forget to end one if statement with a }. That “}” was missing. You can’t have an if inside one. You had something like this:
    if (document.getElementById)
      document.getElementById(‘placeholder’).src = thepic.href;
      if (thepic.title)
      document.getElementById(‘desc’).childNodes0.nodeValue = thepic.title;
      alert(‘This executed the: IF->IF STATEMENT’);
    There should be a “}” right after before the else. I make the same mistake. Make sure you have your “}” in the right places and the correct number of them as well.

    Copy & paste the code below to embed this comment.
  11. There should be two end braces before “else”

    Copy & paste the code below to embed this comment.
  12. Thanks for your advice, and your patience.

    I took another look at the script on but I was unable to find a problem; that is, all the braces (”}”) are in the right place. Take a look at the page and view the script for yourself. You’ll notice that the alerts function just fine, and that the nested if statement (as well as the nested else statement) execute properly. In this page, I’ve commented out the offending lines so that the only thing running is the swapping of the picture and the alerts to track the script.

    Now, if you’ll go to you’ll find the same exact script with the exception that the lines

    document.getElementById(‘desc’).childNodes0.nodeValue = thepic.title;


    document.getElementById(‘desc’).childNodes0.nodeValue = thepic.childNodes0.nodeValue;

    are uncommented. Since the alerts show me where the script is executing I’ve narrowed the problem down to these two lines. In each case, the script runs just fine until we get to one of these lines, when, for some reason, the browser ends up following the link and loading the improperly.

    What could be rwrong with these lines?  :(  I’m just stumped.

    Anyway. Thanks, yet again.

    Copy & paste the code below to embed this comment.
  13. Your code is way too complicated. Instead of childNodes0, use firstChild. It’s the same thing. I don’t know what’s wrong. I haven’t the time to help newbies. I’m writing my own version which is simpler than this.

    Copy & paste the code below to embed this comment.
  14. I told you what was wrong. If you have nested if statements you else if. That’s what’s wrong.

    Copy & paste the code below to embed this comment.
  15. If you just used my DOM API you wouldn’t need the first if.
    Here it is again…
    //Powered by DCScript
    function DOMCall(name) {
    if (document.layers)
    return document.layers[name];
    else if (document.all)
    return document.all[name];
    else if (document.getElementById)
    return document.getElementById(name);
    Call it like so:
    Where “object” is the object’s id.

    Copy & paste the code below to embed this comment.
  16. I tried to put my money where my mouth is by writing an article about combining IE’s and the W3C’s DOMs. It produced quite useful effetcs, but here is what happened:
    ALA Editor: it works in IE? NOOOOOOOOOO!!!!!!!!!!
    So I assume that if it worked, it was too good.

    Copy & paste the code below to embed this comment.
  17. Is there a way to modify this so that there is
    A. a pop up window to see the pics in
    B. a way to tell it to scroll thru a certain number of jpg’s or maybe a particular folder?
    I am thinking that if I just plug in my digital camera, I get a buttload of jpg’s named DSC101, DSC102,DSC103,etc. I would like to not have to label them and reference that label in order to put them online using this javascript.

    Copy & paste the code below to embed this comment.
  18. I thought the article was pretty useful and its simplicity prompted me to quickly create my own strange interpretation, which i’ve called The Germ Gallery at:

    Copy & paste the code below to embed this comment.
  19. “4. …I AM only 14.”
    Which is obvious to the casual observer.


    Useful article – bears directly on a current project – THANK YOU!

    Copy & paste the code below to embed this comment.
  20. Allowing a script to browse through a folder is a security hazard.

    Copy & paste the code below to embed this comment.
  21. Okay, I’m gonna give this one more (final) go. This seems to be working for everybody except me, so obviously something I’m doing is flawed. That said, I’m at a total and utter loss at trying to figure it out—I’m stumped.

    I just looked over the Germ Gallery that Jon showed us. (By the way, it’s very nice. I like it, lots.)  :)  Anyhow, I went through the js.js script you ran on that, Jon, and it is functionally identical to what I am using on this preschool’s gallery test page (at ) and yet, the browser will always end up following the links.

    What is different? What is wrong in my gallery that’s causing this? Anyway…I don’t mean to be a pest, (advance apologies if I am) I just really want to understand what is happening.

    Thanks again.

    Copy & paste the code below to embed this comment.
  22. I can’t get anywhere with that link. I told you what to do. Get rid of the first if statement and replace it with the DOM API (then, no problem with braces plus it becomes more usable). I can’t help you if you won’t listen to me.

    Copy & paste the code below to embed this comment.
  23. Firstly, an onmouseover event should be added to the links making the status bar display something like ‘view (title)’ where title is dynamically extracted from the link’s title attribute. This will minimize confusion for visitors in a javascript-capable browser expecting a new page to load.

    Secondly, non-javascript users should be pointed to a server side version of the same page. Those that commented that this should be done solely on the server side miss the idea that this solution saves bandwidth for both you and your visitors.

    Copy & paste the code below to embed this comment.
  24. This photo gallery provided a quick solution for a simple business’ website. We’re finishing up a complete overhaul of our site and after fighting with complicated javascript (& dreamweaver) that this college student does not understand, this article was the light at the end of the tunnel! Now our “facilities” page will be as cool as the other guy’s ;-)

    Copy & paste the code below to embed this comment.
  25. I had a look at your preschool image gallery code and also ran into issues. You can check out the gallery that I did at and copy the script code that I use. On that page the second pic has a caption that will appear when clicked.

    I am really not sure why your page breaks with the code that you have, but I can assure you that mne works. Try using my script and see if that helps. I origionally thought it may of been the doctype def that you are using on your page, but my page still properly renders and works with the base html 4.01 trans definition. I’m stumped :)

    Copy & paste the code below to embed this comment.
  26. Well Dante, you’ve shown some aspect of maturity by at least trying to be helpful towards another poster.  Who would have thought such compassion would be forthcoming from someone who otherwise gives the impression of being a spiteful troll?

    It is unfortunate that you feel it necessary to jump and stick your oar in whenever knowledge is shared and sad that this web of ours allows you to do so with such unhelpful frequency.  You rail against the ‘flashy script-hacking’ that goes on here.  Well, I’m sorry to say it, but a lot of the sites that go on to be created by those who read and learn here are a damn sight more successful and with a far higher aesthetic value – ie: as an added bonus to looking nice, they WORK! – than your own site, which you are evidently quite proud of.

    Could it be then, that this site of which you are so proud is the same one that brings up an alert if you dare visit with Mozilla berating you for your choice of browser and steadfastly refusing to work in the way it was obviously intended?  I congratulate you on your narrow and counter-productive efforts.

    Physician heal thyself.

    PS. I’m sure PPK is thrilled by your evangelical use of his moniker as a means of shoring up your arguments instead of having actual originality of thought.  Do you pay him the licensing fee?

    Copy & paste the code below to embed this comment.
  27. An interesting bug in, which took me longer to track down than I planned!

    Your script fails when you try to assign some text to

    It’s failing because that node’s a leaf: it doesn’t have any child nodes. The quick’n’dirty fix would be to change ‘’ to ‘some placeholder text’. Then it would have a text node as its first (and only) child.

    As an alternative (or in addition) you could add a little sanity-checking and recovery to the script itself. I am
    not a DOM scripting wizard. But something like the following should work.

    function showPic( theAnchor ) {
    // Assigns the value of theAnchor.href to document.getElementById( ‘placeholder’ ).src
    // And sets the text of document.getElementById( ‘desc’ ) theAnchor’s title or to its text content

    // Returns false on success, true on failure ;)
    // Disclaimer: tested hardly at all and only in Safari1.2 if ( document.getElementById && theAnchor.tagName “A” && theAnchor.href && ( theAnchor.title || ( theAnchor.firstChild ) ) ) {
      myImageElement = document.getElementById( ‘placeholder’ )
      if( myImageElement && (myImageElement.tagName “IMG”) ) {
      myCaptionElement = document.getElementById( ‘desc’ )
      // We probably should sanity-check what kind of element we have here.
      // But there are an awful lot of valid possibilities, so
      // it’s an exercise left to the reader

      myCaptionText = theAnchor.title ? theAnchor.title : theAnchor.firstChild.nodeValue
      myImageHref = theAnchor.href

      myImageElement.src = myImageHref
      if ( myCaptionElement.firstChild ) {
      myCaptionElement.firstChild.nodeValue = myCaptionText
      } else {
      if( document.createTextNode ) {
        myCaptionElement.appendChild( document.createTextNode( myCaptionText ) )
      } else {
        // no caption set. But never mind….
      // image loading should have been ok so
      return false

    //failed so
    return true

    Copy & paste the code below to embed this comment.
  28. I don’t know thy this is so complex.
    if (!document.getElementById)
    var r = false;
    else var r = true;
    At the end:
    return r;
    Why use all that complex if/else code when the above (or adding the DOM API) would’ve done?
    I use a browser detect (very bad desicion, but I needed to). Mozilla and all none-IE browsers totally screw up everything, so I disabled it. It will be fixed in the redesign (if I do it), but for now I punish these browsers. Yes. What a bad designer I am. Can we change the subject?

    Copy & paste the code below to embed this comment.
  29. I recently agreed to make a web page for my wife. I hade coded a little html in the mid-90’s when things were much simpler (and boring by today’s standards). I figured I’d better come up to speed before starting. Wouldn’t you know, of all the web design books at Border’s, I picked Zeldman’s DWWS. Lucky me.

    Imagine my frustration in trying show a LOT of images (my wife Rebecca is a lampwork glass bead artist) AND use css AND make it compliant AND make it smooth. Dang.

    Anyway, I came up with something that is akin to Mr. Keith’s idea but different. Take the code if you find it useful.

    Thank you Mr. Zeldman and other standards proponents.

    Copy & paste the code below to embed this comment.
  30. Actually it’s IE that’s screwed up. Of course it represents the majority of browsers out there, so making sure things work on it is a good thing. But being able to code once and distribute to any client is the ideal. If IE were compliant, then we wouldn’t have to come up with so many hacks just to make a site behave as we expect.

    Finally, if your site is any indication, then yes you are a very bad designer. But then you don’t care about that anyway do you Dante?

    Copy & paste the code below to embed this comment.
  31. Hi, this may be really simple, but I was wondering if it’s possible to either make the image or caption a link?  If so, an example would be greatly appreciated!

    Copy & paste the code below to embed this comment.
  32. Frankly I don’t care about people calling my design bad anymore. People like you don’t visit my site, anyway. My site was aimed at people looking for info on San Francisco History, which flowed smoothly. Maybe that failed, but I’m fixing it. So go ahead and sue me for trying to help people.

    Copy & paste the code below to embed this comment.
  33. Ian, just wanted to express my (belated but still very) sincere thanks to you for figuring out what was wrong with my script there.

    Your suggestions worked perfectly, and they taught me a lot of valuable stuff about JavaScript and the DOM. Thanks many bunches.

    Copy & paste the code below to embed this comment.
  34. I don’t help people. I give maymay a lot of advice, even though I didn’t solve it. And no thank yous.

    Just kidding.

    Copy & paste the code below to embed this comment.
  35. Awesome script! Just what I’ve been looking for.

    I’ve been trying to figure out where I can add a bookmark tag somewhere on this script, so whenever I click on an image it will display <image.jpg> and also make a call to the bookmark on the page.

    Thanks first.

    Copy & paste the code below to embed this comment.
  36. I think this is a great little script.  I was just wondering if it would be difficult to make the image that javascript intercepts a link to a larger image.  So,  when I click on the text link it shows the preview, and then when the preview is clicked (the link that javascript intercepts) it opens a larger version of that image in a new window. 


    Copy & paste the code below to embed this comment.
  37. I applied the techniques in this article to an existing page, and I must have some simple puncuation in the code wrong (even though I cut and pasted most of it)

    Does anyone have a working sample of these gallery using image thumbnails? I may be able to get mine working by looking at someone else’s.

    Copy & paste the code below to embed this comment.
  38. Is it possibile to link the target image to a larger version of the image?

    Copy & paste the code below to embed this comment.
  39. Paul: I successfully executed using thumbnails on this site:

    An interesting note about the caption area… I found that if your placeholder text is say two lines long, and you replace it with a caption that’s 3 lines long you may run into issues with some browsers (Safari being one of them, didn’t test beyond that). The issue I ran into was that the third line gets cut off when you click on an image with a 3 line caption. I kinda had to hack to fix it – by forcing my placeholder text to be extra large, adding a few br’s and a non-breaking space.

    Copy & paste the code below to embed this comment.
  40. Is it possible to format the caption area at all, like adding a in the caption?

    Copy & paste the code below to embed this comment.
  41. Great article, thanks again ALA. I did find a problem in Safari though. If your images are not exactly the same size they will be stretched, matching the size of the largest image (I tried it with images of same height different widths, but assume the reverse is also true). I did not specify height or width in code (exactly the same as in the article) & it works fine in IE5.5 Win, Win/Mac Firbird/Firefox, and Camino. I did not change the javascript at all, just copy and paste from the article. I am running Panther 10.3.3, Safari 1.2.1.

    Copy & paste the code below to embed this comment.
  42. This may be a fairly basic problem for those with more experience, but being new to JavaScripting….

    What I would like is to have the caption provided not by the Title element, but instead along the lines of a PHP include?

    I guess pseudo-code for this would look something like this…


    …where I assume myCaption would be a text string passed to a function within the JavaScript that would then display the contents of the file 01.txt.

    Is this sort of thing possible? Either code and/or pointers to resources/examples would be appreciated.

    Thanks for taking the time to write this article. Its been quite helpful.


    Copy & paste the code below to embed this comment.
  43. Hey Jeremy, thanks for that – very useful – and I even substituted thumnails for the text and it looks neat, but I found a problem….

    You say it works for IE 5+ (PC and Mac), but my version of IE (Mac 5.2.3) opens the larger images like they were a link to another page which means I lose all my lovely page formatting and I’m forced to use the back button.

    Any suggestions why it would do that?

    Copy & paste the code below to embed this comment.
  44. Love this script and would like to use it. It’s not working for me in Netscape 7.1, and I just went through all the comments here. None of the examples work in NS7.1 (except for Rebecca’s beads – absolutely beautiful, by the way!) Works fine in IE6 and Moz.

    Here’s my attempt:

    Here’s a screenshot. I want it to look like it does in IE:

    Would appreciate some help! Thanks!

    Copy & paste the code below to embed this comment.
  45. My bad! There was a problem with my NS profile. AOK now. Love the script! Thanks!

    Copy & paste the code below to embed this comment.
  46. I also love this image gallery. I really need these previous / next buttons though. I thought maybe this can be accomplished using a bit of javascript and using display:none? Or changing the Z-index using javascript? Does anybody know how to do that?

    Copy & paste the code below to embed this comment.
  47. Please only use the following browsers in your comparisons.

    IE 6.1 (fully patched)
    Opera 7.5b/7.23
    Mozilla 1.7b
    Firefox 0.8
    Safari (1.2)

    In case you didn’t know IE 3,4,5, Netscape 4,4.6,4.08,6 are obsolete so let’s not say i hope it can work in any of them.

    Are we ever going to move forward. I might as well bring out my betamax video machine so i can watch the latest Matrix dvd disc on it, watch me start crying when i can’t insert the disc.

    Copy & paste the code below to embed this comment.