Animations

These animations rely on the jQuery .animate() method that we have used before. If you need a reminder, here's the documentation on the animate method and the W3Schools description of jQuery animate().

Carousels

We now know all that we need to understand how to make a cool effect for our automatic slideshow (carousel). The basic ingredients are these:

  1. We'll use CSS to lay out all the images in the slideshow side by side, left to right. This might be really wide, much wider than our browser, but don't worry.
  2. We'll put all the images in a container that is only as wide as one slide, so that the others will stick out to the left and right of the container
  3. We'll use the CSS overflow:hidden to ensure that the ones that stick out will not be seen by the user.
  4. We'll use the position:relative and left properties to move the assembled slides to the left, so that a different one shows.
  5. We can animate that change to the left property, just as we moved the broom above.

Let's take those one step at a time.

All Images Left to Right

We'll put the images in an unordered list. Since each of our slides is 256px wide, the UL will be 1024px wide (though anything wider than that would also work). We'll make the slides float:left so that they'll be arranged left to right.

Here's the HTML code:

  



And the CSS code:





A One-Slide Container

Here's our next version:

The HTML code is unchanged; here is the CSS code, which only adds one rule. You're strongly encouraged to right-click on the image above and do inspect element, so that you can use the Chrome Inspector to see that the other images are all there. Try unchecking the checkbox next to overflow:hidden or width:256px on the #slides2 element.





Animating the Sliding

Now, let's animate the sliding of the entire unordered list. Since this is an editable execution box, try different target values for the left property. Note that negative values move the list to the left, positive value move it to the right. If the target value is a multiple of 256px, the display moves to a slide boundary.


Note that the JS object has a target value, not an amount by which to change. So, to move from slide to slide, we need to calculate the new target value.

Calculating Target Value for Left

If we are keeping track of the index of the current slide in a global variable, say currentSlideIndex, we can use that to calculate the desired target value. Here's a slideshow that does that. (Assume that the currentSlideIndex is initialized to zero when the page loads.)


Note that we take advantage of the fact that when the selector matches more than one element, jQuery returns an array-like value that has a .length property.