简体   繁体   中英

iDangero.us Swiper slide count when loop is true

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?

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
});

this work in both modes, loop or not

var $slideActive = $('.swiper-slide-active');
var realIndex = $slideActive.data('swiper-slide-index');
if(typeof realIndex === 'undefined') {
    realIndex = $slideActive.index();
}

also, the number of total slides in both modes:

var totalSlides = $('.swiper-slide:not(.swiper-slide-duplicate)').length;

Although this question has been answered already, I thought I'd add my working code based off the accepted answer.

Main issue I had with a looping gallery, is if you go back from the first slide, the current slide reads as 0. Possibly because it's a clone?

Anyway, here's a stripped-back (slightly untested) working solution:

(function($) {

    'use strict';

    var gallery;

    gallery = $('#gallery').swiper({
        parallax: false,
        initialSlide: 0,
        direction: 'horizontal',
        loop: true,
        autoplay: 5000,
        autoplayDisableOnInteraction: false,
        speed: 700,
        preventClicks: true,
        grabCursor: true,
    });

    var totalSlides = gallery.slides.length - 2;

    $('#total').html(totalSlides);

    gallery.on('slideChangeEnd', function(instance) {

        var currentCount = (instance.activeIndex - 1) % (totalSlides) + 1;

        if(currentCount === 0) {
            $('#current').html(totalSlides);
        } else {
            $('#current').html(currentCount);
        }

    });

})(jQuery);

Use the above to display current and total slides on your page. Obviously adjust the ID's in your HTML accordingly.

I would think this value of the actual index value should be available in the Swiper API, although it's nowhere to be found, so for now you'll have to roll your own function to get that value.

This function (tested and works) was provided to me in this thread on the Swiper GitHub Issues page: Need a way to get the accurate activeIndex in loop mode

In loop mode active index value will be always shifted on a number of looped/duplicated slides. you can get attribute 'data-swiper-slide-index' with a function like:

function getSlideDataIndex(swipe){
    var activeIndex = swipe.activeIndex;
    var slidesLen = swipe.slides.length;
    if(swipe.params.loop){
        switch(swipe.activeIndex){
            case 0:
                activeIndex = slidesLen-3;
                break;
            case slidesLen-1:
                activeIndex = 0;
                break;
            default:
                --activeIndex;
        }
    }
    return  activeIndex;
}

Usage:

var mySwiper = new Swiper('.swiper-container', {
    direction: 'vertical',
    loop:true,
    onSlideChangeEnd:function(swipe){
        console.log(getSlideDataIndex(swipe))
    }
});

update in 2020:

Say you are using ionic angular: <ion-slides #slider [options]="slideOps" (ionSlideDidChange)="changeSlide($event)"> Then in your typescript:

@ViewChild('slider', {static: true}) slider: IonSlides;
changeBoss(e){
    let realIndex=e.target.swiper.realIndex;
    console.log(realIndex);
  }

This will give you the real index

The simplest way I found is to simply count the number of .swiper-slide before Swiper initialize code runs (and duplicates the slides).

var numOfSlides = document.querySelectorAll(".swiper-slide").length;

 <!-- swiper 6 CSS --> <link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css"> <h4>slider 1</h4> <!-- Swiper --> <section class="swiper-container" data-swiper="projects"> <div class="swiper-wrapper"> <!-- slide --> <a href="#" class="swiper-slide"> <h3> Slide 1 </h3> </a> <!-- slide --> <a href="#" class="swiper-slide"> <h3> Slide 2 </h3> </a> <!-- slide --> <a href="#" class="swiper-slide"> <h3> Slide 3 </h3> </a> </div> <!-- If we need navigation buttons --> <div class="swiper-button-prev"></div> <div class="swiper-button-next"></div> </section> <!-- swiper 6 JS --> <script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script> <!-- swiper JS Initialize --> <script> var numOfSlides = document.querySelectorAll(".swiper-slide").length; console.log("numOfSlides: " + numOfSlides);/* 3 */ var my_swiper = new Swiper('.swiper-container', { slidesPerView: 3, spaceBetween: 12, // Navigation arrows navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, loop: true, }); </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM