Get the index of current slide in Swiffy Slider

276 Views Asked by At

How can I get the index of current active slide in Swiffy slider. Is there a way to access SlideIndex?

1

There are 1 best solutions below

2
user1844646 On

Late answer - but here goes.

If you enable navigation by adding .slider-nav-animation class to the slider instance, the visible slides will get the class .slide-visible class added to them when they are visible.

If you do not add a specific animation, no animation will occur.

You can then use the .slide-visible class in a querySelectorAll to retrieve the visible slide(s).

The below examples will find a list of visible slides - in this example only one slide is shown at a time and hence return a list of 1. If the slider shows 2 or more slides at a time, all will be returned.

window.addEventListener('load', () => {
    const sliderElement = document.getElementById('myslider');
    swiffyslider.onSlideEnd(sliderElement, function() {
        let visibleSlides = sliderElement.querySelectorAll(".slider-container .slide-visible");

        let activeSlideIndex = Array.from(sliderElement.querySelector(".slider-container").children).indexOf(visibleSlides[0]);
        console.log(activeSlideIndex);
    });
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/swiffy-slider.min.js" crossorigin="anonymous" defer></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/swiffy-slider.min.css" rel="stylesheet" crossorigin="anonymous">

<div class="swiffy-slider slider-nav-animation" id="myslider" style="max-width:500px;">
  <ul class="slider-container">
    <li><img src="https://source.unsplash.com/49b9l_29ceA/1600x900" style="max-width: 100%;height: auto;"></li>
    <li><img src="https://source.unsplash.com/nKAglN6HBH8/1600x900" style="max-width: 100%;height: auto;"></li>
    <li><img src="https://source.unsplash.com/E9ZwWcMGzj8/1600x900" style="max-width: 100%;height: auto;"></li>
  </ul>

  <button type="button" class="slider-nav"></button>
  <button type="button" class="slider-nav slider-nav-next"></button>
</div>