I'm using iDangero.us Swiper js for a webpage, and initialization code is as following:
var mySwiper = new Swiper( '.swiper-container', {
direction: 'horizontal',
loop: true,
speed: 600,
nextButton: '.slider-control-next',
prevButton: '.slider-control-prev',
} );
And I need to get current slider index and total count of sliders. Swiper API provides mySwiper.activeIndex property and mySwiper.slides but the problem is that when loop is true they don't give correct index and count.
Is there any way to get these numbers correctly when loop is true?
VhJDi_mqpHw In this page we can use > mySwiper. activeIndex 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 to get the index of current slide.
Combining the destroy parameter with Window. matchMedia() is an effective way to manage Swiper on different screen sizes. Mobile first is optional—max-width, e.g., window. matchMedia( '(max-width:31.25em)' ), will work just as well.
Swiper is a JavaScript library that creates modern touch sliders with hardware-accelerated transitions (utilizing GPU to offload graphic-intensive transitions and create smoother visuals) and excellent native behavior. Swiper is available for vanilla JavaScript, Angular, React, Vue. js, and Svelte.
The number of slides, and thus sometimes the activeIndex
, is "wrong" by design when loops are involved: https://github.com/nolimits4web/Swiper/issues/1205
Best way I could find to get the total number of slides is:
mySwiper.slides.length - 2
You could use that to get the current index (this one is zero-based):
(mySwiper.activeIndex - 1) % (mySwiper.slides.length - 2)
This is not ideal, of course. You could open a GitHub issue and propose adding more convenient ways of accessing these values.
As of May 2016 they have added the realIndex property!
Things to be aware of: 1.) the realIndex property is returned as a string instead of an integer (just in case you need to do math with it) 2.) the realIndex property starts with 0(as it should), unlike activeIndex in loop mode which in my case started with 1
https://github.com/nolimits4web/Swiper/pull/1697
Just adding yet another answer, since Swiper hasn't included the realIndex
property yet. Here is a nice little way of getting the real index when looping, without subtracting a hard coded number (which might easily change).
var realIndex = e.slides.eq(e.activeIndex).attr('data-swiper-slide-index');
Used like this:
var slider = new Swiper('.swiper-container');
slider.on('slideChangeEnd', function(e) {
var realIndex = e.slides.eq(e.activeIndex).attr('data-swiper-slide-index');
// do whatever
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With