jQuery Cycle: Pager and pagerAnchorBuilder

Hey there! I'm currently working on a CLI tool to deploy WordPress apps to DigitalOcean. Check it out! It's free and open source.

One very awesome and useful plugin for jQuery is jQuery Cycle, which pretty much works out of the box, but browsing through the second part of the Intermediate Demos we’ve seen a click transition called Pager, which is somewhat tricky.

Pager is nothing but a few links next to your cycling block with page numbers, which switch the cycle upon click. It’s very useful when you have to create, say a list of services a company provides, with sweet lightboxes (don’t confuse with the Lightbox plugin), perhaps with some images, cycling through their descriptions, yet we’d like our visitors to be able to switch through the services manually, without having to wait. This is exactly what the Pager transition does, but hey, who the hell would want page numbers instead of their services names?

This is where pageAnchorBuilder comes in, and it’s not quite obvious what has to be done to make this work. According to the jQuery Cycle documentation it’s:

pageAnchorBuilder – callback function for building anchor links: function(index, DOMelement)

So here’s a demonstration of how this would work. Let’s setup a quick cycle, with a few options. Perhaps you’ll need more than I listed below ;)

jQuery('#fade').before('<div id="nav" class="nav"></div>').cycle({
	pager: '#nav',
	pagerAnchorBuilder: paginate

So paginate is a callback function which takes two arguments, the index and the DOM element. Using the index will work just fine. Let’s see how this works with text:

function paginate(ind, el) {
	if (ind == 0) return '<span>Service One</span>';
	else if (ind == 1) return '<span>Service Two</span>';
	// and so on

I think that’s pretty straightforward once you understand how it works. Let’s try some images:

function paginate(ind, el) {
	return '<img src="http://whatever.com/services/service' + ind + '.jpg" />';

So name your images service0.jpg, service1.jpg, etc. And my favourite, CSS classes:

function paginate(ind, el) {
	return '<div class="service' + ind + '"></div>';

Then just add a few .service0, .service1, etc. classes in your stylesheet, voila! Hope that helps, and don’t forget about the other useful options. Cheers!

About the author

Konstantin Kovshenin

WordPress Core Contributor, ex-Automattician, public speaker and consultant, enjoying life in Moscow. I blog about tech, WordPress and DevOps.