s

Posts Tagged with "lightbox"

Lightbox JS 2 hacked for AJAX

Jun 23, 2006  -  Comments

At work today I was given the task of implementing Lightbox JS v2.0 on our new website. To its credit, it was extremely easy to get working... almost too easy.

Of course, that's when I encountered a problem. On our portfolio detail page, Shawn put in a neat little AJAX slider for viewing the pictures of each project. The problem arose because the pictures were being generated dynamically after the page had been loaded. For the Lightbox to work, it needed to know about all of the images as the page loaded. Any images generated after that wouldn't work correctly.

I looked around for awhile to see if I could find anyone else who had run into this same problem that maybe had found a workaround. Well, I found several people who were having the same problem, but no one had solved it yet. So, against all odds, I started poking around in the code to see if I could maybe get something working. Below is my step-by-step solution.

First of all, I edited the .js file. Take the following chunk OUT of the file. Delete it, comment it out, whatever. The code is located in the start: function(imageLink) block.

// if image is NOT part of a set..
if((imageLink.getAttribute('rel') == 'lightbox')){
  // add single image to imageArray
  imageArray.push(new Array(imageLink.getAttribute('href'), imageLink.getAttribute('title')));			
} else {
  // if image is part of a set..
  // loop through anchors, find other images in set, and add them to ImageArray
  for (var i=0; i<anchors.length; i++){
    var anchor = anchors[i];
    if (anchor.getAttribute('href') && (anchor.getAttribute('rel') == imageLink.getAttribute('rel'))){
      imageArray.push(new Array(anchor.getAttribute('href'), anchor.getAttribute('title')));
    }
  }
  imageArray.removeDuplicates();
  while(imageArray[imageNum][0] != imageLink.getAttribute('href')) { imageNum++;}
}

Notice: This breaks the ability to add images to a set and cycle through them from within the Lightbox.

The next step is to initialize the myLightbox object. Put the following code at the top of the page that you'd like to use the Lightbox (or alternately, you can just call it in the <head> section).

<script type="text/javascript">
  initLightbox();
</script>

Update: IE will throw an error if you put the above line of code in the middle of a page. The page must load fully before it will successfully evaluate the JavaScript. So, just put the call at the end of all your code.

And last, all we need to do is to call the start() function to make the magic happen. I'm using Rails, so this is how I did it:

<%= link_to_function image_tag('/images/thumbnail.jpg'), "myLightbox.start('/images/fullsize_picture.jpg');" %>

And just substitute /images/fullsize_picture.jpg with the actual path to your image.

I hope this can help someone else out.

Tagged: javascriptlightboxajax