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
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
Now, in an attached
.js file, add the following script code.
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
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
Similarly, you can insert HTML (or even a jQuery DOM object) into the lightbox. Like so:
#lightbox element — if you’re trying to request a website or HTML page, you’ll probably have to remove the
<body/> tags before inserting content into your lightbox window, else the lightbox would simply disappear. An AJAX lightbox request looks a little like this:
- Try it out: Show me the lightbox
- Let’s load some AJAX content: Load the CSS file for this tutorial into a lightbox
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.
Good luck, and happy styling!