Cycle has to be my favorite jQuery plug-in for slideshows/galleries. It’s lightweight, super easy to implement, and it’s highly customizable. The bummer is if you throw just one image at it, it breaks. Up until now I had been using two templates for galleries — one for single image pages and one for multiple image pages. Then it hit me why not use jQuery to check to see how many elements are in a DIV and then spit out navigation if necessary. Bingo! So easy I should have thought of that one sooner.
So how-se work-se?
First grab jQuery and the Cycle plug-in.
Load ‘em up in the header as normal.
1
2
| <script src='path_to/jquery.js' type='text/javascript' ></script>
<script src="path_to/jquery.cycle.js" type="text/javascript"></script> |
And now the fun part.
Cycle has a built in trigger that can be used to target a DIV to cycle and additional triggers for DIV’s to be used as “buttons” for previous and next transitions. For multiple image only galleries, this is super easy place some images in the cycle DIV and add some Previous and Next DIV’s in your template. Then just tell Cycle which ones to use for which. But in our case we want to use a single template for single and multiple image galleries. So this won’t quite work — unless you think busted single image galleries or buttons that don’t work on a page is a good thing…
What we need to do is write some extra code that checks for the number of images on our page and then dynamically add our navigation.
The Check
jQuery has a built in core function called .length. Guess what it does? That’s right checks the number of elements in an object. All we need to do is create a variable to hold this number and then test it to see if it’s larger than 1.
Here we go.
1
2
3
4
5
| var img_no = $('#gallery . *').length;
if( img_no >= 2 ) {
$('#img-nav').append("<span id='prev'>Previous Image<\/span> / <span id='next'>Next Image<\/span>");
} |
Here, I’ve created a variable called img_no and its value is set to the total number of all elements (* = all) within a DIV I’ve given the ID of gallery. I then take this number and first check to see if it is larger or equal to 2. If it is true, I then use another jQuery function called append to add a chunk of HTML to our page within an empty DIV called img-nav — one span with the ID of previous for our previous button and one span with the ID of next for our next button.
Wiring it all up
Now that we’ve got our check set in place all we’ve got left to do is tell cycle what to cycle and what to use as our buttons.
1
2
3
4
| $('#gallery').cycle({
next: '#next',
prev: '#prev'
}); |
The first part $('#gallery').cycle tells our page to to use the gallery DIV as our cycle. Next, I use the built previous and next functions using next: and previous: and tell each of them to trigger their respective ID’s.
And viloa, single template gallery. That simple.