How To Enable Lightbox2 For AJAX Content

One problem you run into when you try to use Lightbox2 together with images that are inserted with Javascript is that the lightbox doesn't work even though you have added the 'rel="lightbox"' attribute to the link. In my case I was building a webshop in Ubercart with a page that loaded product nodes in a div with AJAX. Lightbox2 worked fine when you clicked on the product image and you actually were on the node page, but it didn't work when the product was loaded with AJAX. The reason for this is that Lightbox2 only processes elements on page load, so the new element you have created is never actually detected by lightbox2. 

Fortunately there is an easy fix for this. Let's say you have a div with id="AjaxTarget" in which you load AJAX content. All you have to do is to add this in the jQuery load function to make sure that the content is processed by Lightbox2 after it's loaded with AJAX:

$("#AjaxTarget").load(AjaxSRC, function() {
  //The code in this function is executed after the uri AjaxSRC is loaded in #AjaxTarget
  Drupal.behaviors.initLightbox($(this));
}