How to add CSS transitions to a slideshow only after the slide transition completes

Megan's picture

She has: 11,421 posts

Joined: Jun 1999

The title says it all! An example of what we're trying to do be seen here:

Note how the content animations only start after the slide transition is complete. With a basic CSS transition implementation the transition would occur when the page loads, and would be hidden for the non-active slides.

In this example I used animate.css for the animations and bxslider for the slideshow (the example above uses a different slideshow library). This code could probably easily be adapted for other libraries.

When the slider loads, we turn off all the animations so we can trigger them at the right time. To do this, we add an "off" class which sets the animation-name properly to "none". Then we set an "active" class on the first slide (other slider libraries may do this by default, but bxSlider doesn't). Once that's done, we can remove the "off" class from that slide only to trigger the animations.

Just before the slide transition (onSliderBefore), turn off the animations for the current active slide, make the next slide "active", and remove the "off" class for animated elements on the new active slide.

       auto: true,
       onSliderLoad: function () {
          $('.slider .animated').addClass('off'); // turn off all the animations by adding an "off" class
          $('.slider > li').eq(1).addClass('active-slide'); // add an "active" class to the first slide
          $('.active-slide .animated').removeClass('off'); // turn the animations on for the active slide by removing the "off" class
        onSlideBefore: function (currentSlideNumber, totalSlideQty, currentSlideHtmlObject) {
          $('.active-slide .animated').addClass('off'); // turn animations off for the active slide
          $('.active-slide').removeClass('active-slide'); // remove the active slide class
          $('.slider > li').eq(currentSlideHtmlObject + 1).addClass('active-slide'); // make the next slide the active one
          $('.active-slide .animated').removeClass('off'); // remove the off class for the active slide

And the code for the CSS classes:

.slider { /* remove existing animations */
  display: none;
  -moz-animation-name: none;
  -webkit-animation-name: none;
  -ms-animation-name: none;
  animation-name: none;

I found that hiding the element when the animation is off helped to smooth the transitions; Otherwise there would sometimes be a flash of the element in its original position before the slide transition completed. This could be caused by some of the issue in this case, and you could try taking that out (and the on class out completely).