How to detect current slide in swiper js?
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";
},
},
});
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
its very easy. just use this:
swiper.activeIndex