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().
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:
overflow:hidden
to ensure that the
ones that stick out will not be seen by the user.
position:relative
and left
properties to move the assembled slides to the left, so that a
different one shows.
left
property, just
as we moved the broom above.
Let's take those one step at a time.
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:
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.
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.
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.