Tutorials

How to edit a Lightbox gallery

Lightbox is pretty much the de facto when it comes to interactive photo gallery scripts. This tutorial will show you how to enable it for use with Surreal-powered galleries.

Before you get started, make sure you’re already including the necessary scripts and stylesheets on your page. For details on how to do this, refer to the Lightbox website.

The markup

Surreal generates simple, semantic markup for its photo galleries. In order for them to work with Lightbox, we’ll need to use a bit of JavaScript to shim the HTML.

Lightbox is really easy to setup, so all we need to do is add a data-lightbox attribute to each photo in the gallery. Here’s an example of the markup Surreal will produce:

<div id="my-gallery" class="editable-gallery">
    <a href="full.jpg">
        <img src="thumb.jpg" alt="Your Description">
    </a>
    ...
</div>

And here’s the markup Lightbox wants us to use:

<div id="my-gallery" class="editable-gallery">
    <a href="full.jpg" data-lightbox="gallery-id">
        <img src="thumb.jpg" title="Your Description">
    </a>
    ...
</div>

The shim

To get from the markup that Surreal outputs to the markup that Lightbox requires, we’ll need to do a couple things:

  • Add a data-lightbox attribute to each link in the gallery
  • Copy the image’s alt attribute over to the link’s title attribute

Here’s what the code looks like:

$(document).ready( function() {

    // Don't execute if we're in the Live Editor
    if( !window.isCMS ) {

        // Group images by gallery using `data-lightbox` attributes
        var galleryId = 1;
        $('.editable-gallery').each( function() {
            $(this).find('a').attr('data-lightbox', 'gallery-' + galleryId++);
        });

        // Set the link's `title` based on the image's `alt` attribute
        $('.editable-gallery').find('a').each( function() {
            var alt = $(this).find('img').attr('alt');
            $(this).attr('title', alt);
        });

    }

});

Always place your shim inside a $(document).ready() callback!

How it works

The script loops through each gallery on the page and adds a unique data-lightbox attribute to all the photos inside. This attribute enables Lightbox and tells it to group the photos by gallery so you can use the next and previous buttons.

Since Lightbox doesn’t require any initialization, that’s all you need to do to get it up and running.