How to detect current slide in swiper js?
Asked Answered
S

8

25

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>
Surpassing answered 5/10, 2015 at 9:22 Comment(2)
What information exactly do you want to have from the current image/slide?Hartford
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 :)Surpassing
P
46

its very easy. just use this:

swiper.activeIndex
Parallel answered 26/10, 2016 at 9:31 Comment(5)
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.Spirochaetosis
As a note: this value will be 1-indexed and not 0-indexed.Halftimbered
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.Moonseed
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.Tweeddale
This seems to be the working answer for swiper v5.xVesicant
L
19

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
Lavella answered 31/1, 2019 at 14:20 Comment(0)
G
18

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";
    },
  },
});
Ganoid answered 26/6, 2020 at 17:43 Comment(4)
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.Leafage
@Leafage 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?Ganoid
You can replace instance_swiper with this inside the slideChange method.Leafage
Not true. activeIndex should be used with slides. realIndex is only useful when you want to know which slide is active (the 1st one, the 2nd one, etc.)Reimport
H
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')
Hartford answered 5/10, 2015 at 10:20 Comment(3)
Not recomended.Labelle
@MohammadAyoubKhan, you need to say why or your comment doesn't add value.Bozuwa
@michel-carroll The question is "How to detect current slide in swiper js?", There is an official API for this. We don't JQuery for this. Secondly, your answer not solving the problem.Labelle
D
4

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!!!!

Disillusion answered 13/9, 2022 at 7:8 Comment(0)
C
4

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>
Corm answered 14/11, 2022 at 21:2 Comment(0)
G
1

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


Griffin answered 20/2, 2023 at 23:38 Comment(0)
S
0

If you are using React write a function handleCurrentIndex with the parameter slideId. Then pass the slideId to this function using the inbuilt method onRealIndexChange:

import React from 'react';

export function App(props) {

const handleCurrentIndex = (slideId: number) => {
console.log('slide number:', slideId)
};

return (
<div className='App'>
  <Swiper
    className="mySwiper"
    pagination={{
      type: "fraction",
    }}
    navigation={true}
    modules={[Pagination, Navigation]}
    onRealIndexChange={(element) => handleCurrentIndex(element.activeIndex)}
    slidesPerView={"auto"}
  >   // react code
  </Swiper>

 </div>
);
}
Suzy answered 19/6 at 17:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.