Little Lightbox_me quirk

Using the excellent Lightbox_me jQuery plugin the other day I came across an interesting quirk. When you lightbox an element, Lightbox_me moves that element in the DOM to a container it creates to lightbox it, but when you close the lightbox it doesn’t put it back where it found it.

The Problem

In my case I was using jQuery’s find function to look inside the clicked element’s parent to find the element I wanted to lightbox. This was because I had multiple elements on a page I wanted to lightbox, so I started with something like this:

$('.button').click( function(){
	$(this).parent('.container')
	.find('.lightbox')
	.lightbox_me()
});

Which worked fine when you clicked on the button the first time, but if you closed the lightbox and clicked the same button again, nothing happened.

The Solution

After prodding about for a while I noticed that Lightbox_me was moving the .lightbox element from the .container element, sticking it in another div hidden at the bottom of the DOM, and crucially, leaving it there after the lightbox was closed.

Obviously this meant when the jQuery looked for the element in the parent a second time, it wasn’t there. So the solution was to change the markup so the trigger had a rel attribute that matched the targets ID, meaning it could be found wherever it was in the DOM.

HTML:

<div class="container">
	<a rel="my-lightbox" class="button" href="#">More info</a>
	<div id="my-lightbox" class="lightbox" style="display: none">
		Lightbox content
	</div>
</div>

JS:

$('.button').click( function(){
	$('#'+$(this).attr('rel')).lightbox_me();
})

My thanks to Justin Perry for helping me troubleshoot this issue.

Hi, nice one – only this didnt seem to work for me – i used…

$('#' + ($(this).attr('rel'))).lightbox_me();

thanks for setting me on track though!