Creating a Lightbox Gallery

By Cory LaViska on April 17, 2019

Lightbox is one of the most popular ways to display photos in a gallery. This tutorial shows you how to integrate the original Lightbox 2 with Surreal CMS using code you can copy and paste.

Four by one


Installing Lightbox

There are two ways to install Lightbox. One is to download it and host the files yourself. The other is to use a content delivery network (CDN). In this tutorial, we'll be using the popular CDNJS.

Add the Lightbox stylesheet by placing the following inside the <head> section of your page.

<link rel="stylesheet" href="">

Add these scripts just before the closing </body> tag. If the page already has jQuery, omit the first line!

<script src=""></script>
<script src=""></script>

Congratulations! You've installed everything you need to make Lightbox work on your page. Now we just need to make it work with Surreal CMS.

Integrating Lightbox

The Lightbox documentation tells you to use certain attributes to initialize it, group photos, show captions, etc. You don't need to do that because we're going to use a script that does it for us. Just create your galleries like you normally would without any proprietary attributes.

You can either copy and paste the following script directly into your page or include it from a separate file (recommended if you're using galleries on more than one page).

Make sure to include the script before the closing </body> tag, but after jQuery and Lightbox.

  $(function() {
		// Set custom Lightbox options here. See
      'resizeDuration': 200,
      'wrapAround': true

    // Initialize Lightbox on all galleries (but not if we're in the editor)
    if (!window.isCMS) {
      var i = 0;

      // Loop through each gallery
     	$('.cms-gallery, .cms-editable[data-type="gallery"]').each(function() {
        var gallery = this;

        // Loop through each link in the gallery
        $(gallery).find('a').each(function() {
          var a = this;
          var img = $(a).find('img');
          var caption = $(img).attr('data-caption');
          var alt = $(img).attr('alt');

          // Shim the appropriate attributes for Lightbox
            .attr('data-lightbox', 'gallery-' + i)
            .attr('data-title', caption)
            .attr('data-alt', alt);


If you're using the deprecated .editable-gallery syntax, you'll need to change the jQuery selector that loops through each gallery to $('.editable-gallery').

You might notice the window.isCMS conditional — this is one way we can detect the CMS. We're basically telling Lightbox to run on the live webpage, but not in the editor. (We don't want photos popping up everywhere while we're trying to edit!)

That's it! Now your page is ready to show off its first Lightbox gallery.

If you're having trouble getting Lightbox to work, feel free to contact us for help.