Tutorials

How to edit a Nivo slider

Sliders have become a staple of modern web design, and Nivo Slider is one of the best around. This tutorial will show you how to make your sliders editable with Surreal CMS.

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 Nivo Slider website.

The Markup

Surreal generates simple, semantic markup for its photo galleries. To make them work with Nivo Slider, we’ll need to use a bit of JavaScript to shim the HTML.

Since Nivo Slider uses the image’s title attribute for captions, we’ll need to copy it over from the alt attribute. Here’s an example of the markup Surreal will produce:

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

And here’s the markup Nivo Slider wants us to use:

<div id="my-gallery" class="editable-gallery">
    <img src="full.jpg" title="Caption here">
    ...
</div>

Nivo Slider also supports links around each slide. You can edit or remove them in the photo gallery editor.

The shim

To get from the markup that Surreal outputs to the markup that Nivo Slider requires, we’ll only need to do one thing:

  • Copy the image’s alt attribute over to its 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 ) {

        // Set the `title` attribute based on the `alt` attribute
        $('.nivoSlider').find('img').each( function() {
            $(this).attr('title', $(this).attr('alt'))
        });

        // Initialize the slider
        $(window).load( function() {
            $('#nivo-slider').nivoSlider();
        });

    }

});

Always place your shim inside a $(document).ready() callback and remember to use $(window).load() to initalize Nivo Slider!

How it works

The script loops through each slider on the page and copies over each image’s alt attribute to its title attribute. This tells Nivo Slider to use it as a caption.

Then it initializes the slider according to the options you set, if any. For more information about initializing Nivo Slider, refer to their documentation.