Reputation: 14717
I use JQuery Cycle 2 and need to show the index of a slide when it is displayed.
Here is the HTML:
<div id="slideshow" data-cycle-auto-height="container" data-cycle-slides="> div" >
<div>slide 1</div>
<div>slide 2 </div>
<div>slide 3 </div>
<div>slide 4</div>
</div>
<div id="caption"></div>
Here is the Javascript:
$('#slideshow').cycle({
delay: 0
});
$('#slideshow').on('cycle-before', function (e, optionHash, outgoingSlideEl, incomingSlideEl, forwardFlag) {
var caption = (optionHash.currSlide + 1) + ' of ' + optionHash.slideCount;
$('#caption').html(caption);
});
Here is the fiddle demo:
http://jsfiddle.net/mddc/kKD9S/1/
The problem is that when at page load the first slide is displayed, but the event "cycle-before" is not fired and the first slide seems to be treated at the last one.
What I did is wrong?
Thanks!
Upvotes: 1
Views: 4241
Reputation: 288
Cycle 2 includes the caption
and captionTemplate
options which allow you to add a caption -- including the slide count -- without having to bind to one of Cycle's events.
$('#slideshow').cycle({
caption: '#caption',
captionTemplate: '{{slideNum}} of {{slideCount}}'
});
Check out the Cycle 2 API and caption demo page for more detail.
Upvotes: 1
Reputation: 1453
The 'cycle-before' event only fires before a transition happens. When you initialize a slideshow, there is no transition, so this even will never get called.
Also, since the 'cycle-before' event gets fired before the change of slide, optionHash.currSlide
will always be the previous slide, and since it is 0-indexed, you will be 1 behind.
To fix these issues, change your cycle-before
event to cycle-update-view
event, which gets fired after the slide has been updated, and will also be called after the cycle is initialized:
$('#slideshow').on('cycle-update-view', function (e, optionHash, slideOptionsHash, currSlideEl) {
var caption = 'Image ' + (optionHash.currSlide + 1) + ' of ' + optionHash.slideCount;
$('#caption').html(caption);
});
Here is a fiddle of it working: http://jsfiddle.net/ZY4uR/2/
Upvotes: 6