How can I get the index of the current slide, when the slide is changed?

SomeSillyName picture SomeSillyName · May 9, 2018 · Viewed 13.2k times · Source

I have the following

mySwiper = new Swiper('.my-swiper', {
    direction: 'vertical',
    loop: true,
});
mySwiper.on('slideChange', function () {
    console.log('*** mySwiper.realIndex', mySwiper.realIndex);
});

But realIndex always returns the previous index. So if I'm on the first slide (0) and go to the next, realIndex is 0 when it should be 1. When I go back to the first slide realIndex is 1 when it should be 0. So it seems the event fires before the index is updated. I've tried other events but haven't had any luck. Is there an event that fires after the slide is changed so that I can capture the current slide index?

Answer

Reborn picture Reborn · May 9, 2018

You should use transitionEnd event as Event will be fired after the transition.

see a demo below

var mySwiper = new Swiper('.swiper-container', {
  direction: 'vertical',
  loop: true,
});
mySwiper.on('transitionEnd', function() {
  console.log('*** mySwiper.realIndex', mySwiper.realIndex);
});
.swiper-container {
  width: 100%;
  height: 100%;
}

.as-console-wrapper {
  z-index: 999999 !important;
}

.swiper-slide {
  text-align: center;
  font-size: 18px;
  background: #fff;
  /* Center slide text vertically */
  display: -webkit-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  -webkit-align-items: center;
  align-items: center;
}
<!-- Link Swiper's CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.2.6/css/swiper.min.css">
<!-- Swiper -->
<div class="swiper-container">
  <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 class="swiper-slide">Slide 4</div>
    <div class="swiper-slide">Slide 5</div>
    <div class="swiper-slide">Slide 6</div>
    <div class="swiper-slide">Slide 7</div>
    <div class="swiper-slide">Slide 8</div>
    <div class="swiper-slide">Slide 9</div>
    <div class="swiper-slide">Slide 10</div>
  </div>
</div>

<!-- Swiper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.2.6/js/swiper.min.js"></script>

Note: If you are not able to see the console.log statement output in the snippet, use F12 to see the index of the slide.