RobbAdam
RobbAdam

Reputation: 13

How to apply animations on two elements at once with animated.css

I am working on a simple slideshow where each slide has its own duration. I would like to add transitions between the slides using animate.css by adding and removing classes on the current and the next slides. My problem is that - with my current approach - only the next slide will be animated (it slides in) but the current one is just disappear without any animation. I have tried to detect the end of the current animation and then change(adding/removing) the classes but in that case there was a huge gap between the slides...

How can make sure that two animations plays at once?`

var slides = $this.find('.slide');

slideIt = function(time) {
    setTimeout(function() {

        var duration = slides.eq(nextSlide).data('duration');

        slides.eq(currentSlide)
        .removeClass(animateIn)
        .addClass(animateOut)
        .hide();


        slides.eq(nextSlide)
        .removeClass(animateOut)
        .addClass(animateIn)
        .show();

        slideIt(duration);

        currentSlide = nextSlide; nextSlide ++;
        if (nextSlide == slidesLength) { nextSlide = 0;}

    },time);
};

Thank you for the help in advance!

Ps.: While typing this post I have realized that it must be the .hide() but without it only the first slide displayed.

Upvotes: 1

Views: 463

Answers (2)

Niklas
Niklas

Reputation: 1938

Native CSS animations on two different elements should always run at the same time. But if you hide an element, it disappears before the animation has even started. You have to add a timer for that.

    slides.eq(currentSlide)
    .removeClass(animateIn)
    .addClass(animateOut);
    // save the jQuery instance of the element that should be hidden.
    var $currentSlide = slides.eq(currentSlide);
    // hide this element later
    setTimeout(function() {
      $currentSlide.hide();
    }, 1000); // 1000 for 1000ms, replace that with the duration of the animateOut animation

Upvotes: 1

Niklas
Niklas

Reputation: 1938

If my first answer doesn't satisfy you, because you want so solve that on the CSS side, when there is a second way:

  1. Remove the .hide() in JavaScript.
  2. Make sure your CSS animation ends with a state, there the element cannot be seen anymore (like transform: scale(0) or left: -100%).
  3. Maintain that final state of the CSS animation. To do that, see: Maintaining the final state at end of a CSS3 animation

Upvotes: 1

Related Questions