Apr 1, 2014

Create your own basic lightbox with CSS and jQuery

If you Google "lightbox", you would be greeted by hundreds of plugins, each with its own speciality. Quite often, these plugins are very heavy and contain a lot of functionality that you would probably not require. In most cases, your requirements are very basic and you wonder if it's practical to use a heavy plugin to get the job done. In this tutorial, we will talk about creating your own basic lightbox plugin. Why carry the whole Swiss knife when you just need a pair of scissors?
The lightbox that we are about to create is inspired by the look of the lightbox in this tutorial by Script Tutorials. However, we will discuss it in such a way that enables you to re-use the code in further projects.

Create basic lightbox look

The first step is to create the basic CSS to define the look of our little plugin. The following is the CSS.
.black_overlay{
    display: none;
    position: absolute;
    top: 0%;
    left: 0%;
    width: 100%;
    height: 100%;
    background-color: black;
    z-index:1001;
    -moz-opacity: 0.8;
    opacity:.80;
    filter: alpha(opacity=80);
}

.white_content {
    display: none;
    position: absolute;
    top: 10%;
    left: 10%;
    width: 80%;
    height: 80%;
    padding: 16px;
    z-index:1002;
    text-align: center;
}

.white_content img {
    max-width: 100%;
    max-height: 100%;
    z-index: 1003;
}
Here, the black_overlay class gives the lightbox a translucent background and the white_content class contains the basic image. We fix the size of white_content and let the image contained within it resize itself to fit properly in it. The reason we fix the size of the parent container of the image is to give it a proper position on the page.

Show and Hide lightbox

Notice the display of both the overlay and the content divs have been set to null for now, which essentially doesn’t show them when the page loads. Therefore, we need handlers in JavaScript to show and hide the lightbox. The function to render a lightbox is as follows. Notice that it takes an argument of the path of an image that it needs to show within the lightbox.
var show = function (image_source) {\
    var content = $(".white_content");

    if (!image_source) {
        return;
    }
    $("<img />", {
        "src" : image_source
    }).appendTo(content);

    content.show();
    $(".black_overlay").show();
};
The function to hide the lightbox is as follows.
var hide = function () {
    $(".white_content”).find("img").remove();
    $(".white_content").hide();
    $(".black_overlay").hide();

};
The interesting thing to note here is that we remove (and not just hide) the image within the lightbox before hiding it. This is to ensure that only a single image is displayed at a time (when the lightbox is initialized again at a later stage). An alternative way is to change the source of the image directly when showing the lightbox.
Although we have defined a hide function, we need to make a cross symbol, clicking which would hide the lightbox altogether. In this example, we use the unicode symbol &#10007; to signify a cross symbol. The styling to position it at the top right of the displayed image is as follows.
.white_content a#cross{
    position: absolute;
    right: 0;
    top: 0;
    background-color: #fff;
    height: 20px;
    width: 20px;
    border-radius: 10px;
    cursor: pointer;
    font-weight: bold;
    color: inherit;
    text-decoration: none;
    z-index: 1004;
}

.white_content a#cross:visited, .white_content a#cross:hover{
    text-decoration: none;
    color: inherit;
}
The lightbox essentially looks like the following.
alt text

Bind functions to images on click

Now that we have been successful in displaying and hiding the image previews through a lightbox, we have to bind this function to every image in the page that we wish to show a preview for. We assume that all the images that are to be a part of the lightbox have the same CSS class. We also ensure that the data-source HTML attribute of the img tag contains the path to the larger version of the image to be displayed. For instance, an image tag looks like the following-
<img class="image-lightbox" src="images/1.png" data-source="images/A.png" />
The JavaScript function that initializes the lightbox and binds a function to all images for displaying the lightbox is as follows.
var init = function (lightboxSelector) {
    var lightboxSelector = lightboxSelector || ".image-lightbox",
        lightboxes = $(lightboxSelector),
        content = $(".white_content");

    lightboxes.each(function (index, lightbox) {
        var selector = $(lightbox);

        selector.css({cursor : "pointer"}); // Adding a pointer on hover

        selector.click(function() {
            var image = selector.attr("data-source"); // Getting the image source
            show(image);
        });
    });

Hide lightbox on escape key press

We can go one step further to improve the usability of this plugin by enabling the support to hide the lightbox on pressing the Escape key. It can be achieved by calling our hide() function on a keyup event.
$("body").keyup( function (e) {
    if (e.keyCode == 27) { // Escape key is pressed
        hide();
    }
});

Conclusion

We have successfully created a light-weight lightbox in this post and it would serve the basic purpose image preview very well. However, this plugin is far from complete and there are different possibilities of improvement. To begin with, you could show a list of images at the bottom of the image preview. Secondly, you could add a different type of a gallery if there is a high number of images available in the page. In addition to that, you could add next and previous buttons to the lightbox and enable navigation through the arrow keys.
You can find the code on GitHub and a demo on GitHub pages. Feel free to create a pull request or an issue.

Liked this post? Have any suggestions? Just let me know. Feel free to comment below!

0 responses:

Post a Comment