Reputation: 11668
I'm using Swiper API to let the user swipe across multiple pages on my HTML5/JS/CSS website.
I initialized the swiper (plase note I'm using Framework7 which includes Swiper API as an internal module, the app
object represent the Framework7 instance:
var swiper = app.swiper.create('#swiper', {
speed: 200,
spaceBetween: 0,
initialSlide: 0,
loop: true,
pagination: {
el: '.swiper-pagination',
type: 'bullets',
},
autoHeight: true,
});
I also have three slides on my HTML:
<div class="swiper-container" id="swiper">
<div class="swiper-wrapper">
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
</div>
<div class="swiper-pagination"></div>
</div>
I wrote a listener to listen for page changes: each time the user swipes to the next page, the transitionEnd
event is fired
swiper.on("transitionEnd", function(e){
var slideIndex = swiper.activeIndex;
console.log("I'm on slide no: "+slideIndex);
});
When I try to retrieve the current slide index (swiper.activeIndex
) I get very weird results: I would expect to get a number, either 0, 1 or 2 (the current page index).
If I don't wrap around I get 1,2,3 (ok, not 0-based, perfectly fine I'll add a -1). If I wrap around (Swiper seamlessly swipes in loop, wrapping around the pages) I also get 0, and 4 as indexes and I don't know why.
The documentation says that in loop mode (loop: true
) the active page index works as follow:
Index number of currently active slide
Note, that in loop mode active index value will be always shifted on a number of looped/duplicated slides
Still don't understand that sentence. "shifted on a number of looped slides"?
Inspecting the HTML I can see that Swiper API creates extra "duplicates" slides at the far left and right of the "real" slide sequence, to create the effect of a seamless loop across pages.
But if effectively I just have 3 pages, why I also get indexes 0 and 4 instead of just 1,2,3? (page1 = 1, page2 = 2, page3 = 3)?
Upvotes: 1
Views: 17461
Reputation: 126
With loop enabled, swiper duplicates the first slide to the end, and the last Slide before the first too keep the animation in flow.
3 Pages + 2 Duplicates = 5 Pages (index 0-4)
With swiper.activeIndex
you are accessing the virtual slides, just use swiper.realIndex
for the real index.
Upvotes: 11