Activate lightbox on dynamically added content

I am developing a small portfolio where I can select a category and when I click on it the content (thumbnails) of that category will be shown (this is through an array).

eg.

photography[0] = <a href="..." rel="lightbox" /><img ...  /></a>
photography[1] = <a href="..." rel="lightbox" /><img ...  /></a>

      

The site first shows the contents of all the categories and when I click on a thumbnail it activates the lightbox, however if I select a category and then click on one of the remaining thumbnails it just brings up the image and doesn't open the lightbox image.

This is what the thumbnails look like on initial page load:

<div><a title="..." rel="lightbox" href="http://...yellow-brick-road.jpg" class="thumbnaila"> <img class="thumbnail " alt="" src="http://...yellow-brick-road.jpg" /></a>

      

When selecting a category, it removes the content in the div and replaces it with other content, eg. exactly the same content. (so rel = "lightbox" still exists).

If anyone could help me with this I would love it (I am using jquery btw).

EDIT after Alex Sexton's answer:

$(".thumbnaila").live("mouseover", function(){
    activateLightbox($(this));});

function activateLightbox(dit) {
    $('a[rel="lightbox"]').lightBox({
            overlayBgColor: '#000',
            overlayOpacity: 0.65,
            containerResizeSpeed: 350
    });

      

}

but now when I select a category and select a thumbnail, it loads the right lightbox and also loads an empty lightbox above the one I want, as you can see:

enter image description here

Does anyone know what is causing this?

+2


source to share


2 answers


If you bind links with a regular event handler:

$('a[rel=lightbox]').click(function(e){ ... });

      

Then any new content added after linking will not be captured.



You can either re-run the binding when the content changes, or simply use jQuery event delegation to attach the handler:

$('a[rel=lightbox]').live('click', function(e){ ... });

      

+2


source


You can call many jQuery lightboxes with $ .lightboxName () for example.

$('a[rel=lightbox]').live('click', function(e){
  e.preventDefault;
  $.fancybox({ href : $(this).attr('href') });
  // OR $.colorbox({ href : $(this).attr('href') });
});

      



Note that jQuery now recommends using .on () instead of .live ().

0


source







All Articles