Implementing own slideshow functionality to Colorbox

I have set slideshow:true in Colorbox‘s configuration and Start slideshow link didn’t appear.

I was pretty sure, that this is due to some stupid bug made by me, but because I was on steroids that day, instead of investigating on what is wrong, I decided to write my own implementation of slideshow func.

Code isn’t pretty, but it can be useful for beginners in determining, how events and other stuff around Colorbox works. This example can also be useful for implementing slideshow functionality to other, non-Colorbox, photo gallery libs, that do not have this functionality implemented in core.

The solution is awfuly simple. It narrows itself to checking state of slideshow (whether it runs or not), periodically simulating user click on Next button (if slideshow runs) and updating start/stop link text.

var
    timeoutId = null,
    slideshowCurrent = 0,
    slideshowEnabled = false,
    stopSlideshowText = '".Yii::t('app', 'stop slideshow')."',
    startSlideshowText = '".Yii::t('app', 'start slideshow')."';
    slideshowCount = $('a[rel="colorbox"]').colorbox().length;

function startSlideshow()
{
    slideshowEnabled = true;

    $('.ss-link').text(slideshowEnabled ? stopSlideshowText : startSlideshowText);

    $('#cboxNext').click();

    timeoutId = window.setInterval(function() 
    {
        $('#cboxNext').click();
    }, 2500);

    var originalClose = $.colorbox.close;

    $.colorbox.close = function()
    {
        stopSlideshow();

        originalClose();
    };
}

function stopSlideshow()
{
    slideshowEnabled = false;

    $('.ss-link').text(slideshowEnabled ? stopSlideshowText : startSlideshowText);

    window.clearInterval(timeoutId);
}

$('a[rel="colorbox"]').colorbox(
{
    title: function()
    {
        var
            myArray = new Array(),
            photoTitle = $(this).attr('title'),
            slideshowLinkText = slideshowEnabled ? stopSlideshowText : startSlideshowText;
            slideshowLink = $('<a>' + slideshowLinkText + '</a>').attr('href', '#').addClass('ss-link'),
            downloadLink = $('<a>".Yii::t('app', 'download image')."</a>').attr('href', $(this).attr('href')),
            combinedString = photoTitle + ' [' + downloadLink.prop('outerHTML') + ' | ' + slideshowLink.prop('outerHTML') + ']';

        myArray = $.parseHTML(combinedString);

        $(myArray[3]).on('click', function(e)
        {
            e.preventDefault();

            if(slideshowEnabled) stopSlideshow(); else startSlideshow();
        });

        return $('<div></div>').append(myArray);
    }
});

The only extra Colorbox-code is at the end and it is used to add start/stop link into photo window itself. If you’re fine with having only one link, outside gallery, then above code becomes even more simply.

That’s all folks.

Leave a Reply