Thursday, 2 September 2010

Simple lightbox effect with jQuery

   


There are many lightbox effects available on the web. They may or may not use frameworks like jQuery, they might be in pure css or made in any way you want it. The one I will explain here is very - very! - simple and uses a mix of css styling and jQuery.
Example

First of all, just put a div in the body of your document like this:
<div id="lightbox"></div>
As you can see, I gave an id to it. That is because I need to style the element with this (put it in the head of your document or make it external - whatever you like):
<style type="text/css">
#lightbox { 
  display:none; 
  background:#000000; 
  opacity:0.9; 
  filter:alpha(opacity=90); 
  position:absolute; 
  top:0px; 
  left:0px; 
  min-width:100%; 
  min-height:100%; 
  z-index:1000; 

-->
</style>
Now, the style is actually making the div "invisible" (display: none), the position is absolute with a 100% width and height (in order to cover all the page), and its color is black with opacity set to 0.9.
The div is actually hidden and we only need to make it visible when needed. To do so I suggest to use the jQuery fadein/fadeout method or, if you prefer, the show/hide method.

Include jQuery in your page, inserting this line into the head of your document:
<script type="text/javascript" src="../js/jquery.js"></script>
***Please, change the src part with the correct path to the .js file.***

Then add a function to the page like this:
<script type="text/javascript">
jQuery.noConflict();
function hideLightbox() {
         jQuery("#lightbox").hide();
    }
function showLightbox() {
        jQuery("#lightbox").show();
    }
</script>
Whenever you need to show or hide the div, just call the function. For example you can do it with an onclick event:
onclick="showLightbox()"
And you're done.
This simple example is very useful - even if undoubtedly basic, and very fast. I actually use it in conjuction to the "progress indicator" as explained in a previous post.

10/12/2010: A new addition!
I just discovered that you might encounter some problems if your page has scrollbars. In case your page is long and scrollbars are shown, if you show the lightbox and scroll you will see that the div is not covering everything. I found that temporarily disabling scrollbars is a good solution to that issue. You can then change the two functions hideLightbox and showLightbox this way:
<script type="text/javascript">
jQuery.noConflict();
function hideLightbox() {
         jQuery("#lightbox").hide();
         jQuery("body").css("overflow", "auto");
    }
function showLightbox() {
        jQuery("#lightbox").show();
        jQuery("body").css("overflow", "hidden");
    }
</script>

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.