19

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>
Tushar
  • 85,780
  • 21
  • 159
  • 179
Ravi Ranjan
  • 407
  • 1
  • 3
  • 16
  • What information exactly do you want to have from the current image/slide? – Michel Carroll Oct 05 '15 at 09:38
  • http://www.idangero.us/swiper/api/#.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. thank you everyone :) – Ravi Ranjan Oct 05 '15 at 10:29

7 Answers7

38

its very easy. just use this:

swiper.activeIndex
Timsta
  • 414
  • 4
  • 7
  • 4
    This is the correct and recommeded answer as it uses Swiper to determine the current slide and not some external css class that might not yet have been assigned. – Larzan Nov 29 '16 at 12:24
  • 2
    As a note: this value will be 1-indexed and *not* 0-indexed. – insertusernamehere Dec 02 '16 at 17:56
  • 1
    The thing to note is the returned value is zero-based... so if your first slide is active the return value will be 0, if it's slide 5, return value would be 4. – Ecropolis Mar 05 '17 at 22:03
  • 3
    It should be noted that `swiper.activeIndex` does not match `data-swiper-slide-index` present on the slide. For that you should use `swiper.realIndex` as mentioned below. – Djave Jun 19 '20 at 09:32
  • 2
    This seems to be the working answer for swiper v5.x – Abdalla Arbab Jan 17 '22 at 12:06
16

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 = this.realIndex;
      const currentSlide = this.slides[index_currentSlide]
      //
      currentSlide.style.background = "red";
    },
  },
});
JoSch
  • 869
  • 1
  • 15
  • 35
  • BTW, the instance is bound to `this` within the context of the event handler method, so you don't have to hard-code the variable name: e.g. `this.readIndex`. – Tim Sep 22 '21 at 10:31
  • @Tim thanks for pointing it out. So I can take out the first variable declaration and reduce it to `const currentSlide = this.slides[this.realIndex]`, right? – JoSch Sep 23 '21 at 15:54
  • 1
    You can replace `instance_swiper` with `this` inside the `slideChange` method. – Tim Sep 24 '21 at 08:04
14

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
Torben
  • 479
  • 6
  • 16
9

As far as I can see from their demos, the current slide always has the .swiper-slide-active class on the current slide element.

You can use jQuery selectors to get properties from the active slide. Here's an example of me fetching its image source:

$('.swiper-slide-active img').attr('src')
Michel Carroll
  • 462
  • 2
  • 9
2

If you are using React.js here is how you could get activeIndex:

const swiperRef = useRef(null)
console.log(swiperRef.current.swiper.realIndex)

  const [currentSlide, setCurrentSlide] = useState(0);

  const [isLeftDisabled, setIsLeftDisabled] = useState(true);
  const [isRightDisabled, setIsRightDisabled] = useState(false);

  const updateIndex = useCallback(
    () => setCurrentSlide(swiperRef.current.swiper.realIndex),
    []
  );

// Add eventlisteners for swiper after initializing
  useEffect(() => {
    const swiperInstance = swiperRef.current.swiper;

    if (swiperInstance) {
      swiperInstance.on("slideChange", updateIndex);
    }

    return () => {
      if (swiperInstance) {
        swiperInstance.off("slideChange", updateIndex);
      }
    };
  }, [updateIndex]);


<Swiper
        className="swiper swiper-17-1"
        modules={[Pagination]}
        pagination={{
          type: "fraction",
        }}
        slidesPerView={1}
        ref={swiperRef}
      />

Key thing is you need to clean up evenlistener!!!!

jaehyuk kim
  • 121
  • 7
2

That's how @Timsta solution can be used:

import { Swiper } from "swiper/react";

// state that has the current active index, which can be used to force re-rende other components
const [activeIndex, setActiveIndex] = useState(0);
    

// Trigger active index state update
<Swiper onRealIndexChange={(element)=>setActiveIndex(element.activeIndex)}>
   {children}
</Swiper>
Azzam Michel
  • 573
  • 5
  • 8
0

Here's a straightforward solution to this using onActiveIndexChange.

Using NextJs refs doesn't work. I highly recommend this approach if you are using SSR.

import React, { useState } from "react";
import type { Swiper as SwiperType } from "swiper";

const SwipeComponent: React.FC = () => {
  const [currentIndex, setCurrentIndex] = useState<number>(0);

  const updateIndex = (swiperInstance: SwiperType) => {
    if (swiperInstance === null) return;
    const currentSlide = swiperInstance?.activeIndex;
    setCurrentIndex(currentSlide)
  }

  return (
    <section className="mb-32 mx-16">
      <Swiper
        initialSlide={currentIndex}
        onActiveIndexChange={updateIndex}
      >
     <SwiperSlide>
     ...
     </SwiperSlide>
   </Swiper>
  </section>)
}


Franco Petra
  • 688
  • 7
  • 18