Friday 19 November 2010

jQuery: AJAX and lightbox effect combined

   


What I'm going to show you how to use AJAX technology to get content for a container and use a lightbox effect to show it.
What we want is to populate a target container upon user request with an external page as source. Then we are going to show the fetched content with a lightbox effect (putting the requested content on top of everything).
We can use jQuery to manage all the operation in a quite simple way.

Let's get directly to the code and I will explain everything.


First of all, we create the destination container:
<div class="domMessage" id="div_example"></div>
That is going to be our target. We can use a css style to give it the look we want:
.domMessage {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 14px;
    text-decoration: none;
    background-color: #346FED;
    text-align: justify;
    color: #FFFFFF;
    padding: 0px;
    border: 2px solid #ddd;
    display:none;
    z-index: 1001;
    position:absolute;
    top:50%;
    left:50%;
    float:left;   
    width:60%;
    height:60%
}
Please notice that the last part of the above code is absolutely important:
  1. the container is hidden (display:none;),
  2. z-index is set to 1001 (it will be in front of anything),
  3. the position is absolute.
Now that we have the target container, we can insert the lightbox:
<div id="lightbox"></div>
We style the above div with:
#lightbox {
     display:none;
     background:#000000;
     opacity:0.9;
     filter:alpha(opacity=90);
     position:fixed;
     top:0px;
     left:0px;
     width:100%;
     height:100%;
     z-index:1000;
     cursor:wait;
}  
The div will be hidden, and with a z-index just below the domMessage div (1000).
Ok, now we have all the containers ready to be used. The domMessage will be populated with the content of an external page, while the lightbox will hide the background.
We can handle all the procedures from two functions.
First of all, include the jQuery library in the <head> section of your main page:
<script type="text/javascript" src="js/jquery.js"></script>
**Please change the src according to your jquery library path**
Then, insert the following code snippet:
<script language="JavaScript" type="text/javascript">
    var example_check = 0;
function loadContent(VarDest,VarUrl, VarAdded) {
   
    if(eval(VarAdded) == 0){
        $.ajax({
            type: "GET",
            dataType: "html",
            url: VarUrl,
            scriptCharset: "iso-8859-1",
            cache: false,
            success: function (data) {
                $(VarDest).append(data);
                eval(VarAdded + "= 1");}
        });
    };
   
    $(VarDest).fadeIn();
    $("#lightbox").show();
}
function closeContent(VarDest) {
         $(VarDest).fadeOut();
         $("#lightbox").hide();
}
</script>
Now that is quite complicated to explain. I will try, for every important line.
var example_check = 0; 
This is the check we will use to see if the container is already populated or not. We start setting it to 0, which means it is not filled.
function loadContent(VarDest,VarUrl, VarAdded) {
The function will have 3 parameters. VarDest is the name of the destination container, VarUrl is the path/name of the file to get, VarAdded is the name of the variable used to check if the container is already populated or not.
if(eval(VarAdded) == 0){
We check if the container is already filled or not. If not, we proceed with the AJAX request. We use eval because we are actually passing a dynamic variable (VarAdded is a variable containing a variable).
We start the AJAX request and then, with:
$(VarDest).append(data);
we append the content to out destination (VarDest). After that, we set VarAdded to 1:
eval(VarAdded + "= 1");
because we now have just populated the container and we don't want to populate it again (on a second eventual request).
$(VarDest).fadeIn();
We show the target container.
$("#lightbox").show();
This will make the lightbox div visible.

The second function (closeContent) is used to hide the target container. Before seeing that part, we have to create the trigger for the loadContent function. In my example I use a simple text (put it where you want in your page):
<div align="center" id="cto" onclick="javascript: loadContent('#div_example','example.asp', 'cs_example')" >Click to open domMessage</div>
We style the above div with:
#cto{
    cursor: pointer;
    cursor: hand;
}
Clicking the div will start the loadContent function passing the 3 requested parameters:
  1. '#div_example' is our destination div;
  2. 'example.asp' is the external page we want to use to populate the target div;
  3. 'cs_example' is the variable we use to check if the container is already populated or not.
The external page can contain whatever you like, however I suggest to put something there to allow the closing of the destination div (hiding it and hiding the lightbox div).
In our example, the external page starts with a closing image (choose the one you like):
<div class="close_btn" align="right"><img src="images/close_icon.jpg" alt="Close" onclick="javascript: closeContent('#div_example')"/></div>
We style the image with:
.close_btn {
    overflow:hidden;
    height:5%;
}
Clicking the image will trigger the closeContentlightbox.
The external page will contain another div (<div class="inner" id="inner"></div>) where you will put the text you want to show. This div have a style as well:
.inner {
    overflow:auto;
    height:95%;
    padding-right:20px;
}
Please note that the close_btn div has height:5% and the inner div has 95%. This is made to allow the overflow only in the inner div. You might have to play around with those two values just to evaluate the desired effect.
If the user wants to open the destination div once again, the loadContent function will evaluate the varAdded parameter and will not get the example.asp content (because already there). It will just show the destination div.
I hope that it is clear enough, however if you try to use the above code, you will probably understand it better.

Enjoy!

10 comments:

  1. Hi can you telll me how to combine lightbox and jquery grey fade out effect on my blog?
    I add some code from:
    http://introblogger.blogspot.com/2010/07/image-mouseover-fadegreyscale-effect.html


    ...

    ...

    Can You help me?
    I add the 'grey script' and lightbox stop work now:/ Thanks in advance:]

    ReplyDelete
  2. Patryk, it is quite difficult for me to help you because I cannot see your blog and especially the code behind it. I visited the link of the "grey script" and I believe it should work perfectly. Can you just remove one of the two effect and see if they are working alone? If so, there might be some sort of conflict in your code.

    ReplyDelete
  3. there is some prob wid code i think
    it is not getting displayed properly.
    For what "url: VarUrl" is used??
    there is no use of it??

    ReplyDelete
    Replies
    1. It is used by jQuery AJAX. See the jQuery help for more info.

      Delete
  4. Hi,
    After implementing the code I observed that the lightbox always show the same data set that it fetched for the first time. Is there any way around to overcome this problem.
    Thanks in advance

    ReplyDelete
    Replies
    1. You need to change the content every time. Otherwise the content will always be the same.

      Delete
  5. Hi.
    I click on to show the preview of invoice data- the content is always different on every click. But lightbox result is always the same. Please advice.
    Regards
    K

    ReplyDelete
    Replies
    1. It is quite difficult for me to help you. I am sure it works because I've built an entire small web site working on the above ideas. Please try to narrow the problem, copying exactly the examples. There must be a mistake and I think it's in the example.asp. That page must change, for each div. So in the end you should have different div with different external pages (example1.asp for div1, example2.asp for div2 etc.).
      The example.asp page must not contain any < html > or < head > tags: just the styles and the divs (image and inner).
      I hope it helps.

      Delete
    2. I wish to show the code to you, But this page cannot accept any HTML . How would I show you the code?

      Delete

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

However, I do answer to all the comments.