Extending WordPress Slideshow

In a previous post I had created a system for making automated slideshows using only jQuery and the built-in WordPress attachments system. While it certainly works, I today changed around the behavior to instead read the images off sequentially, rather than picking one at random.

The trouble with the random selection, at least with the way I had previously coded it, was that especially for small sets of photos, you’d get the same image twice in a row. By keeping track of a counter variable, you can easily get by this. There are, of course, many other ways to do this, though I want to share:

function advanceSlide(item_class, display_id)
{
var display = $('#' + display_id);
display.empty();

var items = $('.' + item_class);
display.append(items.eq(currentItem).clone());
display.children('.' + item_class).fadeIn();

currentItem = (currentItem + 1) % itemCount;
}

$(document).ready(function()
{
var item_class = 'gallery-item';
var display_id = 'gallery-display';
$('#gallery-1').before('<div id="' + display_id + '"></div>');
$('#' + display_id).attr('style','height:500px');
$('.' + item_class).hide();

itemCount = $('.' + item_class).size();
currentItem = 0;

advanceSlide(item_class, display_id);
setInterval("advanceSlide('" + item_class + "','" + display_id + "')", 4000);
});

The main difference is in using global variables to keep track of which image we’re on, and to keep track of how many images total we have. The modulo operator (%) is a standard method for restarting the count once it reaches a certain level, which is what you want when you reach the end of the list of images.

Although I generally do not like global variables, using them in the above (announced by having the variable declaration without the var keyword, in JavaScript) certainly does cut down on the complexity of the code.

Tags: ,

Leave a Reply