Artvader
Artvader

Reputation: 958

How to add a class to the container in swiper.js when slide has reached the end?

I'm using swiper.js for a particular project, for the most part it's ok. However I wanted to adjust the container's look based on the when the slide is at the beginning, middle or at the end.

I know there's an event to watch for it, but I don't know how to add the class to the container DOM that triggered that particular event because there are several carousels in the same page. I tried using this.addClass('reached-end') and $(this).addClass('reached-end'), but it didn't work.

<div class="carousel-container">
  <div class="swiper-wrapper">
    <div class="swiper-slide">First Slide</div>
    <div class="swiper-slide">Last Slide</div>
  </div>
</div>   
var cardDeck = new Swiper('.carousel-container', {
  on: {
    reachEnd: function () {
      //add  .reached-end to .carousel-container
      // $(this).addClass('reached-end') // this didn't work
      // this.addClass('reached-end') // this didn't work either
    }
  }
});

Upvotes: 1

Views: 6114

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

From the documentation you can see that all the events run under the scope of the Swiper instance, not the container element as your code expects:

Please note, that this keyword within event handler always points to Swiper instance

As such, you will need to select the element within the event handler. Note that Swiper provides both $el and $wrapperEl properties for this, depending on exactly which parent you want to target.

var cardDeck = new Swiper('.carousel-container', {
  on: {
    reachEnd: function () {
      this.$el.addClass('reached-end');
    }
  }
});

Upvotes: 4

Related Questions