Alessandro Dotti Contra

Linux/Unix DevOps


JQuery simple lightbox

Lightbox is a javascript effect that allows displaying of large images in a modal way. It's simple and effective, degrades well if javascript support is disable and can be easily added to any web site. This is an example implementation.

We use a simple list of links to the images we want to display.

<ul>
	<li><a class="lightbox" href="img1.png">Image 1</a></li>
	<li><a class="lightbox" href="img2.png">Image 2</a></li>
	<li><a class="lightbox" href="img3.png">Image 3</a></li>
</ul>

CSS snippet

Please note that most of the styles are applied to the elements at runtime, so we just need to define some defaults.

#lightbox_overlay {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	color: #FFFFFF;
	background: #000000;
}

#lightbox_container {
	position: absolute;
	color: #000000;
	background-color: #FFFFFF;
}

Code snippet

First of all we define two functions, one for showing the image and one for removing the lightbox when the image is clicked.

function showImage() {
	//Timeout is set for those browsers which don't wait for the image
	//to be completely loaded before doing stuff
	setTimeout(function() {
		//Evalute image container position (center it)
		var top = ($(window).height() - $('#lightbox_container').height())/2;
		var left = ($(window).width() - $('#lightbox_container').width())/2;

		//Position the image container and fade it in
		$('#lightbox_container')
			.css({
				'top': top + $(document).scrollTop(),
				'left': left
			})
			.fadeIn();
	}, 1000);
}

function removeLightbox() {
	//Fade out and remove overlay and lightbox
	$('#lightbox_overlay, #lightbox_container')
		.fadeOut('slow', function() {
			$(this).remove();
		});
	
	//Restore the scrollbars
	$('body').css({
		'overflow-x': 'auto',
		'overflow-y': 'auto'
	});
}

Now we define the main lightbox function we are going to call when the links are clicked.

function lightbox(clicked) {
	//Hide the scrollbars
	$('body').css({
		'overflow-x': 'hidden',
		'overflow-y': 'hidden'
	});

	//Create the overlay
	$('<div id="lightbox_overlay"></div>')
		.css({
			'top': $(document).scrollTop(),
			'opacity': '0'
		})
		.animate({'opacity': '0.5'}, 1000)
		.appendTo('body');

	//Create the image container (and hide it)
	$('<div id="lightbox_container"></div>')
		.hide()
		.appendTo('body');

	//Add the image
	$('<img />')
		.attr('src', $(clicked).attr('href'))
		.load(function() {
			showImage();
		})
		.click(function() {
			removeLightbox();
		})
		.appendTo('#lightbox_container');

	//Add the description box 
	$('<div id="lightbox_description">
		<p>Click on the image to close it</p>
		</div>').appendTo('#lightbox_container');
}

Final step: bind the lightbox() function to the links click event.

<script type="text/javascript">
$(document).ready(function() {
	$('a.lightbox').click(function(e) {
		lightbox(this);
		e.preventDefault();
	});
});
</script>
View demo