Create a Lightbox with jQuery and CSS

Create a Lightbox with jQuery and CSS

The “lightbox” is a unique and useful design tool when used properly. It allows designers to present information that is totally independent from the site theme, and it is especially useful when displaying information that is loaded via AJAX requests (often negating the need for additional post-backs on your pages). There are countless ways to implement lightbox functionality into your site, and almost every option I’ve ever seen is weighed down by extraneous functionality or useless transition animations. It’s quite easy to create your own lightboxes with minimal effort. This tutorial can serve as a quick and easy template to get you started.

The CSS Style

There are two elements you’ll have to implement into your design in order to create a lightbox — CSS and Javascript. We’ll take care of the CSS style first, as it’s the most simple to implement. On your page or in an attached style sheet, add the following CSS styles:

#lightbox {
	position: absolute;
	top: 0;
	left: 50%;
	width: 500px;
	margin-left: -250px;
	background: #fff;
	z-index: 1001;
	display: none;
}
#lightbox-shadow {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: #000;
	filter: alpha(opacity=75);
	-moz-opacity: 0.75;
	-khtml-opacity: 0.75;
	opacity: 0.75;
	z-index: 1000;
	display: none;
}

What we just did: we established two styles. One style is for the lightbox that actually appears on the page (#lightbox). The second style is for lightbox background (#lightbox-shadow). We have made this background dark and semi-transparent in order to dim the site’s content as it appears behind the lightbox.

The jQuery Script

The real work is done via our simple jQuery script. We have two JavaScript functions that will handle displaying and hiding our lightbox. First, make sure you have attached the jQuery library to your page:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

Now, in an attached .js file, add the following script code.

/****************************************
	Barebones Lightbox Template
	by Kyle Schaeffer
	kyleschaeffer.com
	* requires jQuery
****************************************/

// display the lightbox
function lightbox(insertContent, ajaxContentUrl){

	// add lightbox/shadow <div/>'s if not previously added
	if($('#lightbox').size() == 0){
		var theLightbox = $('<div id="lightbox"/>');
		var theShadow = $('<div id="lightbox-shadow"/>');
		$(theShadow).click(function(e){
			closeLightbox();
		});
		$('body').append(theShadow);
		$('body').append(theLightbox);
	}

	// remove any previously added content
	$('#lightbox').empty();

	// insert HTML content
	if(insertContent != null){
		$('#lightbox').append(insertContent);
	}

	// insert AJAX content
	if(ajaxContentUrl != null){
		// temporarily add a "Loading..." message in the lightbox
		$('#lightbox').append('<p>Loading...</p>');

		// request AJAX content
		$.ajax({
			type: 'GET',
			url: ajaxContentUrl,
			success:function(data){
				// remove "Loading..." message and append AJAX content
				$('#lightbox').empty();
				$('#lightbox').append(data);
			},
			error:function(){
				alert('AJAX Failure!');
			}
		});
	}

	// move the lightbox to the current window top + 100px
	$('#lightbox').css('top', $(window).scrollTop() + 100 + 'px');

	// display the lightbox
	$('#lightbox').show();
	$('#lightbox-shadow').show();

}

// close the lightbox
function closeLightbox(){

	// hide lightbox and shadow <div/>'s
	$('#lightbox').hide();
	$('#lightbox-shadow').hide();

	// remove contents of lightbox in case a video or other content is actively playing
	$('#lightbox').empty();
}

 

Ready for Lightboxing

Once you have the CSS and script into place, you can call your new lightbox(); function from anywhere within your design. It’s as easy as calling the lightbox from an anchor tag:

<a href="javascript:lightbox('Hello!');">Show me the lightbox</a>

Remember, clicking anywhere on the “shadow” <div/> will hide the lightbox — you could easily add a “close” button to your lightbox by connecting it to the closeLightbox(); JavaScript function.

Similarly, you can insert HTML (or even a jQuery DOM object) into the lightbox. Like so:

<a href="javascript:lightbox('<p><strong>Rich</strong> content works too!</p>');">Show me the lightbox</a>

Finally, you can even use this simple lightbox function to insert AJAX content. Please keep in mind that my JavaScript function simply inserts the entire result into the #lightbox element — if you’re trying to request a website or HTML page, you’ll probably have to remove the <html/> and <body/> tags before inserting content into your lightbox window, else the lightbox would simply disappear. An AJAX lightbox request looks a little like this:

<a href="javascript:lightbox(null, 'http://foo.com/readme.txt');">Show me the lightbox</a>

The Demo

If you’re on a fast connection, you may not notice, but the AJAX link actually reads “Loading…” in the lightbox a split-second before the content actually appears. This can be useful to give users feedback while the AJAX request is processing. Please note that I’ve added a bit of styling to my demo (namely padding on the lightbox to make it appear less cluttered).

Make it Shine

You’ll probably want to modify the CSS and other elements of this lightbox in order to suit your site’s design and style. If you’re working with a lot of AJAX content, you may want to even replace the temporary loading element with an animated spinner image, or something of the like.

To help you get started, you can download the CSS and JavaScript referenced in this tutorial here:

Good luck, and happy styling!

Advertisements

20 comments on “Create a Lightbox with jQuery and CSS

  1. I’ve learn a few just right stuff here. Certainly price bookmarking for revisiting. I surprise how a lot effort you put to make such a wonderful informative website.

  2. But a smiling visitant here to share the love (:, btw outstanding design. “Better by far you should forget and smile than that you should remember and be sad.” by Christina Georgina Rossetti.

  3. I like what you guys are up too. Such smart work and reporting! Keep up the superb works guys I have incorporated you guys to my blogroll. I think it’ll improve the value of my site 🙂

  4. Wow, incredible blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your site is magnificent, let alone the content!

  5. I have been exploring for a little bit for any high quality articles or blog posts on this kind of area . Exploring in Yahoo I at last stumbled upon this web site. Reading this info So i’m happy to convey that I’ve a very good uncanny feeling I discovered just what I needed. I most certainly will make certain to do not forget this web site and give it a look regularly.

  6. Thanks a bunch for sharing this with all folks you actually recognise what you’re talking approximately! Bookmarked. Please additionally visit my website =). We can have a hyperlink trade arrangement between us!

  7. I feel that is among the such a lot significant information for me. And i am satisfied studying your article. However wanna observation on some normal things, The site taste is ideal, the articles is truly nice : D. Excellent process, cheers

  8. Thanks for the helpful content. It is also my belief that mesothelioma has an extremely long latency interval, which means that warning signs of the disease won’t emerge till 30 to 50 years after the original exposure to asbestos fiber. Pleural mesothelioma, which can be the most common kind and is affecting the area round the lungs, might result in shortness of breath, upper body pains, including a persistent cough, which may lead to coughing up maintain.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s