Search code examples
javascriptcarouselanimate.csssplidejs

Splide.js text animation between slides with animate.css classes


I use splide.js carousel and i want to animate text caption between slides using animate.css.

I use splide events: https://splidejs.com/guides/events/

This is the code i use:

document.addEventListener( 'DOMContentLoaded', function () {

  var splide = new Splide( '.slider', {
    type: 'fade',
    perPage: 1,
    autoplay: true,
    focus: 'center',
    trimSpace: false,
    rewind: true,

  } ).mount();

  splide.on( 'active', function() { 
    const element = document.querySelector('.title');
    element.classList.add('animate__animated', 'animate__fadeInRight');
    } );

  splide.on( 'inactive', function() {   
    const element = document.querySelector('.title');
    element.classList.remove('animate__animated', 'animate__fadeInRight');  
    } );

});

Codepen example: https://codepen.io/haralake/pen/YzQObEK

The first slide get the class but others don't. I guess i'm using events the wrong way, but i don't know where the issue is.


Solution

  • I use splide on my own site which is the only reason I'm familiar with it, but their documentation is horrible. The event callback functions have an event object that contain the slide index triggering the event (such as becoming active or inactive). Yes the active event does run every time a slide changes, but look at what element you're querying. You grab the first element with class 'title' regardless of what's active. The following should do what you want.

    splide.on( 'active', function(e) {  
        const element = document.querySelectorAll('.title');
        element[e.index].classList.add('animate__animated', 'animate__fadeInRight');
    });
    
    splide.on( 'inactive', function(e) {    
        const element = document.querySelectorAll('.title');
        element[e.index].classList.remove('animate__animated', 'animate__fadeInRight');  
    });