Wesley Todd

Code, Clay & Pixels
I am an artist and these are my media.
Some of the things I make are useful {Websites, Mugs}.
Others are beautiful {Vases, Pictures, Sculptures}.
Hopefully a few fit into both categories.

SimpleBox – A jQuery Lightbox

Of course I know that this is nothing exciting, another jQuery Lightbox...whoopty frickin do...Why make a new one? Sometimes you just need a standard, no-frills and simple solution that you can use as a base for other more complicated functionality. That is what this lightbox is, simple and basic. Most other lightbox plugins that I have come across provide robust functionality that make very complex things into a very simple installation. This is great when you need a modal window video gallery or want to pull a video from YouTube. But what about when you are building custom social sharing functionality what needs just the most basic lightbox implementation? This is when I say, KISS (Keep It Simple, Stupid).

If it is so simple, then what does it do? You, the developer, provide the lightbox element as a jQuery object and the plugin hides it until an event is triggered. When this event happens, the plugin creates an overlay, positions the lightbox and shows them both. While the lightbox is open it listens for an event that will cause the lightbox to close and closes it upon command. Sounds pretty simple right?

How well does it work? This is the next most important question. A few things have been taken into consideration here. Number one is browser support and number two is performance. The main issued here is that modal windows which rely on JavaScript to position them jump when you scroll and require more resources. The best solution to position them is using the css rule position: fixed;. However, this is not supported in IE 6 and is not correctly implemented in the modern mobile browsers. So we have to do a feature detect for fixed positioning support and fall back to absolute positioning and JavaScript when it is necessary. A big thanks to Juriy Zaytsev for this bit of code which creates a fixed position element and tests to make sure it moves correctly upon scrolling:

function isFixedSupported(){
    var container = document.body;
    if (document.createElement && container && container.appendChild && container.removeChild) {
        var el,
            originalHeight,
            elementTop,
            isSupported;
                    
        el = document.createElement("div");
                    
        if (!el.getBoundingClientRect) {
            return false;
        }
        el.innerHTML = "x";
        el.style.cssText = "position:fixed;top:100px;";
        container.appendChild(el);
        originalHeight = container.style.height, originalScrollTop = container.scrollTop;
        container.style.height = "3000px";
        container.scrollTop = 500;
        elementTop = el.getBoundingClientRect().top;
        container.style.height = originalHeight;
        isSupported = elementTop === 100;
        container.removeChild(el);
        container.scrollTop = originalScrollTop;
        return isSupported;
    }
    return false;
}

Unfortunately, this code incorrectly returns true for iOs Safari and the Android Browser. To fix this I added in a temporary hack to force absolute positioning for these user agents:

var isiMobile = navigator.userAgent.match(/(iPad)|(iPhone)|(Android)/i) != null;
if(base.options.use_fixed  && !isiMobile){
    base.bFixedSupported = base.fncFixedPositionSupported();
}else{
    base.bFixedSupported = false;
}

So what is the actual browser support for this after all the hacktastic fun?

Browser Support

  • Internet Explorer: 6.0 +
  • FireFox*: 3.6 +
  • Chrome*: 13 +
  • Safari*: 5.1 +
  • iOS Safari*: 4.2 +
  • Android*: 2.3 +
* May work in older versions, but has not been tested.

Usage

The most important thing about this plugin is that it is completely independent of the lightbox markup. This gives you as the developer a great freedom to use this code in a ton of situations. A very basic example can be found on the example page. But who wants a simple example? So here is a more comprehensive example.

The HTML

<a id="button" href="#">Click Me</a>

Literally that is all we are going to need. Obviously you would have that in the context of an HTML document...

The CSS

#lightbox {
    background: #fff;
    border: 2px solid #444;
    padding: 25px;
}
#lightbox .image {
    float: left;
    margin: 0 15px 15px 0;
}
#lightbox .social-buttons {
    margin: 15px 0 0;
}

All of this is purely for the sake of the example. You can style your lightbox however you want. There is no included styling other than the positioning applied by the JavaScript. As you can see, we are going to add some social buttons and an image. There really isn't much to it though.

The JavaScript

Here is the important part, dynamically creating the HTML for the modal window. Remember to include jQuery and the SimbleBox script before this next script. For this part I will need you to imagine that we have a server which will return some JSON for us to use in creating this modal window. We are going to send an AJAX request to get the information we need, then build the lightbox and use the plugin to show it. So first let's setup the AJAX request:

function show_lightbox(){
    $.ajax({
        url: 'http://example.com/imaginary-json.php',
        async: true,
        dataType: 'json',
        data: {action:'get-lightbox'},
        success: function(data){
            //The JSON returns the url which we are going to like,
            //the url of an image to show and a message.
            var like_url = encodeURI(data.like),
                message = data.message,
                img_url = data.img;

            //Create the html markup as a jQuery object
            var html = '<div id="lightbox"><img src="';
            html += img_url;
            html += '" class="image"/><p>';
            html += message;
            html += '</p><div class="social-buttons">';
            html += '<iframe src="http://www.facebook.com/plugins/like.php?app_id=0&href=';
            html += like_url
            html += '&layout=button_count&width=100&action=like&height=21">';
            html += '</div></div>';

            var $lb = $(html);

            //This is where you could do some custom things with the lightbox before showing it

            $lb.jwtSimpleBox({
                show_function    : 'fadeIn',        //Change the show animation
                show_duration    : 500,             //Change the show duration
                show_now         : true,            //Because this is being triggered
                                                    //dynamically we don't want to wait
                                                    //to show the lightbox
                hide_cb          : function(base){  //Remove the element from the DOM on close
                    base.$el.remove();
                }
            });

            //This is where you would do some custom things to the lightbox after showing it.

        }
    });
}
$('#button').click(function(){
    show_lightbox();
    return false;
});

So we have a lightbox created dynamically based on some information returned from an AJAX request. Now that we have the lightbox element created all we have to do is use the plugin to show the lightbox. This removes the content of the lightbox from the functionality. This is different in respect to many other JavaScript lightboxes in that it makes it possible to have HTML content that is already on the page become the content inside the lightbox. This can make the content search engine friendly as well as usable without Javascript.

Could we use a plugin that does ALL of this? Of course...but what about the next time that you need the lightbox content to be different? Maybe you wanted an image gallery or a video? Then you would either have to load a larger and more robust plugin or re-write the core lightbox functionality to support the new content.

Plugin Page

Join The Discussion...

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>