Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect current slide in swiper js?

Working with swiper js for a slider and want to detect the current image/slide. how i can detect with HTML and JS? any idea?

<div class="swiper-container">
    <div class="swiper-wrapper" align="center">
        <div class="swiper-slide">
            <img src="images/card_gold.png" width="80%" align="middle" onclick="desc(\'' + card1 + '\')">
        </div>
        <div class="swiper-slide">
            <img src="images/card_platinum.png" width="80%" align="middle" onclick="desc(\'' + card2 + '\')">
        </div>
        <div class="swiper-slide">
            <img src="images/card_silver.png" width="80%" align="middle" onclick="desc(\'' + card3 + '\')">
        </div>
    </div>
    <!-- Add Arrows -->
    <div class="swiper-button-next"></div>
    <div class="swiper-button-prev"></div>
</div>
like image 962
Ravi Ranjan Avatar asked Oct 05 '15 09:10

Ravi Ranjan


2 Answers

As of May 2016 they have added the realIndex property!

swiper.realIndex

https://github.com/nolimits4web/Swiper/pull/1697

Notice:

  • property is returned as a string
  • property starts with 0, unlike activeIndex in loop mode which in my case started with 1
like image 114
Torben Avatar answered Oct 31 '22 04:10

Torben


Expanding on the answers that already refer to the realIndex property, here is a method for fetching the current slide's element by using realIndex as well as the slides property (an array containing all slides of the instance) to get the slide-element:

let index_currentSlide = instance_swiper.realIndex;
let currentSlide = instance_swiper.slides[index_currentSlide]

You can make use of this when constructing the instance by (for example) fetching the current slide whenever the slideChange event occurs and manipulating the element:

const instance_swiper = new Swiper(".swiper-container", {
  on: {
    slideChange: function () {
      const index_currentSlide = instance_swiper.realIndex;
      const currentSlide = instance_swiper.slides[index_currentSlide]
      //
      currentSlide.style.background = "red";
    },
  },
});
like image 24
JoSch Avatar answered Oct 31 '22 04:10

JoSch