Loading...

Using Spicing Up the Bootstrap Carousel with CSS3 Animations

View: 629    Dowload: 0   Comment: 0   Post by: hanhga   Category: HTML-CSS template   Fields: Other

There are times, however, when a lightweight carousel with minimal options is all you need. In this case, if your project uses Bootstrap, the popular open source front-end framework, you won’t need to look any further than the Bootstrap Carousel component.

In this article, I’m going to show how to add some fun animation effects to the Bootstrap Carousel, while still making sure this handy JavaScript component remains bloat-free and quick to implement.

Introducing Animate.css

As rewarding as crafting my own animation effects can be, I’m going to use a well-known open source CSS3 animation library most aptly called Animate.css, by Dan Eden.

This is so that I can focus on the task at hand, rather than on explaining the code for CSS3 animations. However, if you want to delve into that topic, you’ll enjoy the CSS3 Animations series here on SitePoint, by Craig Buckler.

Using Animate.css requires two steps:

  1. Include animate.min.css in the  section of your HTML document.
  2. Add the classes of animated yourchosenanimation to the elements you intend to animate on your web page.

In the latter step you would replace “yourchosenanimation” with the class name corresponding to any of the numerous animations you see on the Animate.css website.

The Bootstrap Carousel component has three main sections:

  • The Carousel indicators track the overall number of slides, give users a visual clue of the position the slide currently being viewed occupies, and offer an alternative navigation for the slider.
  • The Carousel item, located inside a wrapper container with a class of .carousel-inner, represents each individual slide. It’s inside each item that you place your images. You can also add captions to your slides. The nice thing is that you can put pretty much any HTML element inside a container with the class of carousel-caption and Bootstrap will take care of the styling and formatting. It’s these captions that we’re going to animate.
  • Finally, the Carousel controls are the navigation arrows that enable users to access the next and previous slides.

Bootstrap Carousel structure

If you’d like to explore the Bootstrap Carousel component in detail, be sure check out Creating JavaScript Sliders Using Bootstrap 3, by Syed Fazle Rahman.

To keep this demo simple, I’m not going to add images to the carousel. The focus is all on the carousel captions as the object of our animations.

Building the HTML Structure

If you’re following along, here’s what you need to include in your project:

  • jQuery
  • Bootstrap’s CSS and JavaScript
  • Animate.css
  • A custom stylesheet and JavaScript document (both of which we will edit in this article)

To speed up the process, grab a starter template from the Bootstrap website and add the necessary files.

Here’s the code for the Bootstrap Carousel:

<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">

  <!-- Indicators -->
  <ol class="carousel-indicators">
    <li data-target="#carousel-example-generic" data-slide-to="0" class="active">
    </li>
    <li data-target="#carousel-example-generic" data-slide-to="1"></li>
    <li data-target="#carousel-example-generic" data-slide-to="2"></li>
  </ol>

  <!-- Wrapper for slides -->
  <div class="carousel-inner" role="listbox">

    <!-- First slide -->
    <div class="item active">
      <div class="carousel-caption">
        <h3 data-animation="animated bounceInLeft">
          This is the caption for slide 1
        </h3>
        <h3 data-animation="animated bounceInRight">
          This is the caption for slide 1
        </h3>
        <button class="btn btn-primary btn-lg"
                data-animation="animated zoomInUp">Button</button>
      </div>
    </div><!-- /.item -->

    <!-- Second slide -->
    <div class="item">
      <div class="carousel-caption">
        <h3 class="icon-container" data-animation="animated bounceInDown">
          <span class="glyphicon glyphicon-heart"></span>
        </h3>
        <h3 data-animation="animated bounceInUp">
          This is the caption for slide 2
        </h3>
        <button class="btn btn-primary btn-lg"
                data-animation="animated zoomInRight">Button</button>
      </div>
    </div><!-- /.item -->

    <!-- Third slide -->
    <div class="item">
      <div class="carousel-caption">
        <h3 class="icon-container" data-animation="animated zoomInLeft">
          <span class="glyphicon glyphicon-glass"></span>
        </h3>
        <h3 data-animation="animated flipInX">
          This is the caption for slide 3
        </h3>
        <button class="btn btn-primary btn-lg"
                data-animation="animated lightSpeedIn">Button</button>
      </div>
    </div><!-- /.item -->

  </div><!-- /.carousel-inner -->

  <!-- Controls -->
  <a class="left carousel-control" href="#carousel-example-generic"
     role="button" data-slide="prev">
    <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="right carousel-control" href="#carousel-example-generic"
     role="button" data-slide="next">
    <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>

</div><!-- /.carousel -->

If you’ve included the correct files and you open the above code in your browser, you should be able to see a nice working carousel, and all this without writing a single line of JavaScript. If you didn’t add any images to the carousel, just assign a min-height value to the .carousel .item selector in your CSS document to prevent the carousel from collapsing.

The elements inside the carousel caption that we’ll be animating have a data-animation attribute added to them with the specific animation class name as their respective value.

If you’d like to experiment with other animations from the Animate.css library, feel free to replace the values in the data-animation attribute with your chosen animation class names.

We’ll be using the data-animation attribute in our JavaScript code shortly.

Although a simple auto-playing carousel is what you could be looking for in some cases, for this demo we’re after more control.

As a first step in this direction, delete the data-ride="carousel" attribute from the .carouselelement. The data-ride attribute initializes the carousel without having to write any JavaScript code. However, we’re going to take control of the carousel using JavaScript, therefore the data-ride attribute won’t be necessary.

Now, give free rein to your creativity and style the carousel captions according to your taste. The style rules that I’m going to focus on here are those relevant to the smooth working of this demo.

More specifically, we’re taking control of the animation-delay property, which will define when each animation will start (note that vendor prefixes are omitted for brevity).

.carousel-caption h3:first-child {
  animation-delay: 1s;
}

.carousel-caption h3:nth-child(2) {
  animation-delay: 2s;
}

.carousel-caption button {
  animation-delay: 3s;
}

The snippet above ensures that the elements start their animation sequentially. There’s room for play here. For instance, you can choose to start animating the first two headings at the same time, followed by the button animation. It’s up to you, have fun with it!

Writing the jQuery

Let’s start by initializing the carousel. In your custom JavaScript file, add this code snippet:

var $myCarousel = $('#carousel-example-generic');

// Initialize carousel
$myCarousel.carousel();

We’ve set the carousel in motion. Next, we tackle the animation.

To animate the captions in the first slide, the script has to fire as soon as the page finishes loading in the browser. However, to animate subsequent slides as they come into view, our code will have to fire on theslide.bs.carousel event. This means that the same code will be used twice: on page load and on theslide.bs.carousel event.

Because we love the DRY principle, we’re going to wrap our code in a function and attach it to the appropriate events as required.

Here’s the code:

function doAnimations(elems) {
  var animEndEv = 'webkitAnimationEnd animationend';
  
  elems.each(function () {
    var $this = $(this),
        $animationType = $this.data('animation');

    // Add animate.css classes to
    // the elements to be animated 
    // Remove animate.css classes
    // once the animation event has ended
    $this.addClass($animationType).one(animEndEv, function () {
      $this.removeClass($animationType);
    });
  });
}

// Select the elements to be animated
// in the first slide on page load
var $firstAnimatingElems = $myCarousel.find('.item:first')
                           .find('[data-animation ^= "animated"]');

// Apply the animation using our function
doAnimations($firstAnimatingElems);

// Pause the carousel 
$myCarousel.carousel('pause');

// Attach our doAnimations() function to the
// carousel's slide.bs.carousel event 
$myCarousel.on('slide.bs.carousel', function (e) { 
  // Select the elements to be animated inside the active slide 
  var $animatingElems = $(e.relatedTarget)
                        .find("[data-animation ^= 'animated']");
  doAnimations($animatingElems);
});

There’s quite a lot going on in the chunk of code above, so let’s break it down.

Looking into the doAnimations() Function

The doAnimations() function performs the tasks described below.

It starts by caching a string in a variable containing the name of the animationend event. This event tells us, you might have guessed, when each animation ends. We need this bit of information because each time the animation ends, we remove the Animate.css classes. If we fail to do this, the carousel captions will be animated only once, that is, just the first time the carousel shows a particular slide.

var animEndEv = 'webkitAnimationEnd animationend';

Next, our function loops over each element that we want to animate and extracts the value of thedata-animation attribute. As you recall, this value contains the Animate.css classes that we need to add to our element in order to animate it.

elems.each(function () {
  var $this = $(this),
      $animationType = $this.data('animation');    
  // etc...
});

Finally, the doAnimations() function dynamically adds the Animate.css classes to each element that we want to animate. It also attaches an event listener that fires only once, when the animation ends. After the animation ends, the Animate.css classes that we just added are removed. This ensures that the next time the carousel comes back to the same slide, the animations take place again (try removing this bit of code and you’ll see the animations happen only once).

$this.addClass($animationType).one(animEndEv, function () {
  $this.removeClass($animationType);
});

As soon as the page loads in the browser, we animate the content inside the first slide like so:

var $firstAnimatingElems = $myCarousel.find('.item:first')
                           .find("[data-animation ^= 'animated']");  
doAnimations($firstAnimatingElems);

Int this code, we begin by finding the first slide. From there, we select the content we want to animate inside the caption by using the values of the data-animation attribute starting with animated. We then use the piece of data thus obtained as an argument in our doAnimations() function and let the function do its job.

After the content in the first slide has performed its animations, we pause the carousel.

$myCarousel.carousel('pause');

This is a feature of the Bootstrap Carousel designed to stop it from cycling. You’re free not to pause the carousel, but you run the risk of annoying your website visitors.

In this case, I recommend you make sure the carousel doesn’t cycle to the next slide until all animations on the active slide have run their course. You can control this by setting the “interval” option in the initialization code as follows:

$myCarousel.carousel({
  interval: 4000
});

I my opinion, an infinitely looping carousel with captions jumping around each time a slide comes into view is far from ideal.

Animating the carousel captions as each slide becomes visible requires the steps described below.

First we attach an event listener to the slide.bs.carousel event. According to the Bootstrap Carousel documentation:

$myCarousel.on('slide.bs.carousel', function (e) { 
  // do stuff...
});

Next we select the active slide, that is, the slide currently in view, and from there we find the elements we wish to animate. The code below uses the .relatedTarget property of the slide.bs.carousel event to get hold of the active slide.

var $animatingElems = $(e.relatedTarget).find("[data-animation ^= 'animated']");

Finally, we call our doAnimations() function, passing our selection of the elements to be animated as an argument.

doAnimations($animatingElems);

 

Using Spicing Up the Bootstrap Carousel with CSS3 Animations

There are times, however, when a lightweight carousel with minimal options is all you need.

Posted on 14-03-2016 

Comment:

To comment you must be logged in members.

Files with category

 
File suggestion for you
Loading...
File top downloads
Loading...
Loading...
Codetitle - library source code to share, download the file to the community
Copyright © 2018. All rights reserved. codetitle Develope by Vinagon .Ltd