3

I'd like to build a jQuery Cycle slideshow with pagination in the format of "current_slide/total_slides" as seen here

I'm assuming I'd use pageAnchorBuilder to show the current and total slide numbers and then onAfter to update the current slide number?

Can anyone help with this? Thanks!

Joe B
  • 33
  • 1
  • 3
  • The answer you chose is actually incorrect. You can embed your slides as any element inside your slide holder (ie
    • ...) therefore relying on counting children does not work except in the simplest cases.
    – lucuma Jul 24 '13 at 22:44

2 Answers2

5

I recommend using jQuery Cycle plugin. Imagine that slides are an ordered list:

<ol class="slides">
    <li class="slide">...</li>
    ...
</ol>
<a id="prev"></a><span id="counter">1 / 1</span><a id="next"></a>

you can obtain the total number of slides by calling:

var total = $('.slides').children().length;

Then we need to update the counter after slide changes:

$('.slides').cycle({
    after(el) {
        const currentSlideNo = $(el).index();
        $('#counter').text(currentSlideNo + ' / ' + total);
    },
    prev: $('#prev'),
    next: $('#next'),
});
Michał Miszczyszyn
  • 11,835
  • 2
  • 35
  • 53
  • This may be a simple question...but your approach using index() returns a zero-based result...so my first image appears as "0 / 5". Is there a way to use a 1-based counting method? Simply adding "+1" after index() doesn't seem to be reliable. Thanks! – Joe B Apr 19 '12 at 15:10
  • Yeah, sure, didn't think of that. after $('#counter').text... change currentSlideNo to (currentSlideNo+1). It should work, if not, additional parseInt may be required. – Michał Miszczyszyn Apr 19 '12 at 16:18
  • using `$('#counter').text(currentSlideNo+1' / '+total);` results in an Unexpected string error. I've worked around it by using 'onPrevNextEvent' instead of the 'after' function, and setting `var currentSlideNo = $(slideElement).index() +1;` – Joe B Apr 19 '12 at 17:13
  • There's a typo... it should be `(currentSlideNo+1+' / '+total)` of course. – Michał Miszczyszyn Apr 20 '12 at 22:10
  • Working with `.index()` doesn't seem reliable. The `after` callback function gets the current slide in the `options` object. I think this works better. – michelgotta Oct 18 '12 at 13:44
4

There is no need to calculate the total and slideindex because the jquery cycle plugin will already return those to you in the after event.

 after: function(currSlideElement, nextSlideElement, options, forwardFlag) {

    $('#counter').text((options.currSlide + 1) + '/' + (options.slideCount));
 }

Here is a jsfidde: http://jsfiddle.net/lucuma/Dhqdc/2/

lucuma
  • 18,247
  • 4
  • 66
  • 91
  • The other answer is actually incorrect as you can provide a selector to determine which elements are slides therefor $().children won't work. Better to use the plugin api – lucuma May 06 '13 at 11:47