Monday, March 02, 2009

Super Easy Fast-Forward Reverse Carousel with YUI 3!

I've been mucking with YUI 3 and playing around with carousels using their Animation Utility. If you don't know what a carousel is, here's a suggested reading. Our carousel is a little different. Ours rewinds when we reach the end or fast-forwards when we're on the first and go to the last element. We come up with something like this --



Play with it. It'll work on all the big browsers -- IE, FF, Safari and Opera. Think of the carousel as a queue with a start and an end. So, all we're doing is traversing the queue from the front to the end and back again. It's a simple exercise which we probably did in Data Structures 101!

Go ahead and view the source. The code is easy to understand and it'll just be another YUI 3 example.


There are several important points to remember. We'll use an HTML template to represent the carousel. Our JavaScript will reference this for the animation --
            <div class="view-port">
<ul class="carousel">

<li>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</li>

<li>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
</li>

<li>
<div>9</div>
<div>10</div>
<div>11</div>
<div>12</div>
</li>

<li>
<div>13</div>
<div>14</div>
<div>15</div>
<div>16</div>
</li>

<li>
<div>17</div>
<div>18</div>
<div>19</div>
<div>20</div>
</li>

<li>
<div>21</div>
<div>22</div>
<div>23</div>
<div>24</div>
</li>

</ul>
</div>
We've grouped our items -- this is the unordered list -- and each group represents the "viewable" area and each list contains content. Content of course can be anything -- a div, another list, an image, a table or a collection of all those things. It's the unordered list with the class name "carousel" that we'll be animating. The important thing to remember is that we can easily calculate the width of each list by using the element's "offsetWidth" property. There's no need to hardcode anything. This is the width of the viewable area and this is also the distance which we'll move by. If we view the source, this is the variable WINDOW_WIDTH.

Another thing that we're doing is that we never set the animation object's "from" attribute. This is because "from" is implicit. Once we move to a position, we know where we're at ( obviously! ). We just need to specify where we want to move and so throughout the animation, we just set the "to" attribute. In reality, we can always get our current position by calling the method getX() on the element that we're moving.
                function scrollLeft() {

if (_currentIndex === _startIndex) {

_currentXPosition = -1 * WINDOW_WIDTH * (TOTAL_PAGES - 1) + _carousel.getX();
_currentIndex = TOTAL_PAGES - 1;

} else {

_currentXPosition = _carousel.getX() + WINDOW_WIDTH;
--_currentIndex;

}

}

where _carousel is the unordered list that we're moving.

That's it. It's pretty straightforward and easy. Feel free to use the code and have fun!