As you already know that I've been working on improving the performance of my website and I needed a simple solution to create light-box effect for Live-Chat on this website. I had many options to choose from available jQuery plug-ins however, the idea was to optimize the code with minimal use of heavy third-party scripts and CSS. Moreover, Only thing I needed was a light-box effect without any other functionality.

So I created the light-box effect with a few lines of code using CSS and jQuery.

View Demo

Let's start coding :)

xHTML Code

Place this code within <body></body> tags where ever you like.

<a id="show-panel" href="#">Show Panel</a>
<div id="lightbox-panel">
<h2>Lightbox Panel</h2>
You can add any valid content here.
<p align=center><a id="close-panel" href="#">Close this window</a></p>

<!-- /lightbox-panel -->
<div id="lightbox"></div>
<!-- /lightbox -->

First line of the above code is a link with id "show-panel" which will display the "light-box" and the "lightbox-panel" DIVs, similarly on line 7 we have a link with ID "close-panel" to hide these DIVs. This will be handled by jQuery of course.

#lightbox-panel will hold the content to be dispalyed and #lightbox will add a transparent background behind our content panel. Let's write some CSS code to stylize these two DIVs before we add the functionality to our links with jQuery.

CSS Code

You can add this code within the document's <head></head> tag or in any linked style sheet.

* /Lightbox background */
#lightbox {
/* Lightbox panel with some content */
#lightbox-panel {
  padding:10px 15px 10px 15px;
  border:2px solid #CCCCCC;

Note: The z-index value for #lightbox-panel should be greater than z-index value of #lightbox to display it above the transparent background and both should have the property display as none so they should not show up by default or if the users have Javascript disabled in their browsers.

Let's put some life to our code with jQuery.

jQuery Code

You can add this code within the document's <head></head> tag and we are done.

    $("#lightbox, #lightbox-panel").fadeIn(300);
    $("#lightbox, #lightbox-panel").fadeOut(300);

Pretty simple, huh!!

Could it get easier than this?

Once you click the link with ID "show-panel" it will display both the DIVs with some nice fade effect and if you click the link with ID "close-panel" it will hide these DIVs.

I hope you enjoyed this little trick to create simple light-box effect with CSS and jQuery and You are most welcome to share your inputs and code in the comments below.