So, the other day I was building a popup dialog box based on the principals seen in most light boxes. I wanted the box to be centered top and bottom and left and right. The obvious choice was to use jQuery, but I wanted something that would be reusable.

Seemed like there were 3 parts to the problem.

  1. Center the dialogue box

  2. Grey out the background

  3. Hide all of the lightbox when someone clicks off the lightbox

Centering the dialogue box

I found a start at Stack Overflow, while a great start, it seemed to be missing a few things that I was looking for.

jQuery.fn.UnseenCenter = function() {
   this.css({
     "position": "absolute"});
   this.css({
     "top": (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px",
     "left": (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px"
   });
   return this;
};

The code extends the jQuery Framework and creates a new function called ‘UnseenCenter’ that can be called in association with any element on the page. Note: when getting calculating the element’s size we are using the jQuery outerHeight() and outerWidth() to insure that we are taking padding and margins into account.

For the box itself, we can use a div that is styled with CSS. Now, we want to insure that the jQuery code is unobtrusive so we will use classes and ids to manage onClick() events that show and hide the lightbox. In this case I chose a class called ‘UnseenLightbox’ that will be used to associate and element with the click event.

To enable multiple lightboxes on the same page we need to create some code that will allow us to target specific lightbox content with the click() event. To do that I created a class/ID hi-bred solution. Every element that has the class ‘UnseenLightbox’ will also have a class with a particular format ‘UnseenTarget-DivID’ where the ‘DivID is the id of the lightbox element to be displayed.

Here is the HTML so far:

<a href='#' class='UnseenLightbox UnseenTarget-DivID'>click here for lightbox</a>
<div id="DivID" class='Unseenlightbox-content' style="display:none;">
    You can put anything here:
    <ol>
            <li>Images</li>
            <li>Lists</li>
            <li>Forms</li>
    </ol>
    Use CSS to make this look great!
</div>

We’ll use the $(document).ready(handler) to run through the dom when loaded and connect the onClick events for each of the elements to the targeted lightbox content. To do that, we’ll look at each ‘UnseenLightbox’ classed element and check that it has a ‘UnseenTarget-DivID’ class. If it does, we have all the information we need to set an onClick event targeting the correct lightbox div. It looks like this:

$(function() {
    $('.UnseenLightbox').each(function(index) {
        $(this).click(function() {
            targetDivID = null;
            $.each($(this).attr('class').split(' '), function(index, item) {
                if (this.indexOf("UnseenTarget-") === 0) {
                    targetDivID = item.replace('UnseenTarget-', '');
                }
            });
            if (targetDivID != null) {
                $('#' + targetDivID).UnseenLightboxShow();
            }
        });
    });
});

Greying the background

This is one of these things that is useful to make sure the user focuses on the dialogue and does not get distracted. We’ll also make it so that if the user clicks on the greyed background that the dialogue will close. We’ll do this with a div that we’ll .append() to the dom with jQuery. We can check to insure we only do this once by checking to see if the element exists in the dom.

jQuery.fn.exists = function() {
    return jQuery(this).length > 0;
}
if (!$('#UnseenBackgroundDiv').exists()) {
    $('body').append('<div id="UnseenBackgroundDiv">');
}</div>

Now that we have the background div in the dom, we’ll want to place it so that it covers the whole background. We’ll do that by setting the some CSS attributes with the jQuery .css() function. We’ll need to know how large the document is. We can use $(document).height() and $(document).width() to get that. We are going to want to absolute position the background and set its z-index so that it will be over everything but the lightbox.

Now, just so that it is pretty, we can use the .fadeTo(), .fadeIn(), and .fadeOut() effect functions from jQuery. We can use these on the targeted content div as well as the grey background.

jQuery.fn.UnseenLightboxShow = function() {
    if (!$('#UnseenBackgroundDiv').exists()) {
        $('body').append('<div id="UnseenBackgroundDiv">');
        $('#' + 'UnseenBackgroundDiv').click(function() {
            $(this).UnseenLightboxHide();
        });
    }
    $('#' + 'UnseenBackgroundDiv').hide();
    $('#' + 'UnseenBackgroundDiv').css({
        "top": 0,
        "left": 0,
        "height": $(document).height() + "px",
        "width": $(document).width() + "px",
        "position": "absolute";
        "background-color":"black",
        "z-index": "9000"
    });
    $(this).css("z-index", '9100');
    $('#' + 'UnseenBackgroundDiv').fadeTo('slow', .7, function() {});
    $(this).fadeIn('slow', function() {}).center();
};</div>

Close the Lightbox

Most of the heavy lifting is complete. We’ll create just one more jQuery function called ‘UnseenLightboxHide’ that when called will fade all the lightbox elements out. We’ll also need to add some code to call the function when someone clicks on the background.

jQuery.fn.UnseenLightboxHide = function() {
    $('#' + 'UnseenBackgroundDiv').fadeOut('slow', function() {});
    $('.Unseenlightbox-content').fadeOut('slow', function() {});
}
$('#' + 'UnseenBackgroundDiv').click(function() {
    $(this).UnseenLightboxHide();
});

Conclusion

I hope this tutorial was helpful. There are a couple interesting problems we solved today. Something we did not implement that would be very helpful would be a quick couple of lines that would recenter the lightbox when someone resizes the browser window. It would be fairly easy to refactor the code and implement jQuery’s .resize() function.

Demo and Files

You can look at a quick demo can be found at Lightbox Demo.

The javascript file can be found Here.

Comments