How to detect current slide in swiper js?

2 min read 07-10-2024
How to detect current slide in swiper js?


Unveiling the Current Slide: Mastering Swiper.js Navigation

Swiper.js is a popular JavaScript library that makes creating beautiful, interactive slideshows and carousels a breeze. But how do you know which slide is currently being displayed? This is where understanding the activeIndex property comes in handy.

Understanding the Problem

Imagine you have a Swiper.js instance showcasing a product gallery. You want to display a specific button only when a particular product slide is active. How do you programmatically determine which slide is visible?

Scenario and Code:

Let's say you have a basic Swiper.js setup with three slides:

<div class="swiper-container">
  <div class="swiper-wrapper">
    <div class="swiper-slide">Slide 1</div>
    <div class="swiper-slide">Slide 2</div>
    <div class="swiper-slide">Slide 3</div>
  </div>
</div>

<script>
  var swiper = new Swiper('.swiper-container', {
    // Your Swiper configuration
  });
</script>

The Key: The activeIndex Property

Swiper.js provides the activeIndex property, which tells you the index of the currently visible slide. The index starts from 0 for the first slide.

Code Example:

Let's modify our example to display a "Buy Now" button only when the second slide is active:

var swiper = new Swiper('.swiper-container', {
  // Your Swiper configuration
});

// Function to handle slide change
swiper.on('slideChange', function () {
  if (swiper.activeIndex === 1) {
    document.getElementById("buyNowButton").style.display = "block";
  } else {
    document.getElementById("buyNowButton").style.display = "none";
  }
});

Here's what's happening:

  1. We use the on('slideChange', function(){...}) method to trigger a function whenever a new slide becomes active.
  2. Inside the function, we check if swiper.activeIndex is equal to 1 (second slide).
  3. Based on the condition, we show or hide the "Buy Now" button using JavaScript.

Beyond Basic Use: Advanced Applications

The activeIndex property is a powerful tool with various applications:

  • Dynamic Content: You can load different content based on the active slide, creating unique experiences.
  • Navigation Control: Implement custom navigation buttons that jump to specific slides using swiper.slideTo(index).
  • Custom Styling: Style elements differently based on the active slide, adding visual interest.
  • Data Manipulation: Fetch data or perform actions related to the displayed slide.

Conclusion

The activeIndex property is a cornerstone of Swiper.js navigation control. By leveraging its power, you can create dynamic, engaging slideshows and carousels that respond to user interaction and provide a seamless experience.

Resources: