Search code examples
javascriptjqueryanimationround-robin

Round robin scroll of div


Consider the following arrangement (jsfiddle):

         <------- Full width occupied ------->
---------------------------------------------------------
| Div A | Div B | Div C | Div D | Div E | Div F | Div G | .... H, I, J
---------------------------------------------------------

/* There are Div H, I & J currently not visible */

Button: Left Scroll 
Button: Right Scroll

If user presses, Left Scroll - Div H, I & J enter the display area in a sequence, but after J instead of the Div moving deeper towards the left, the it should cycle back to A then B and so on.

I have been able to achieve the motion (see fiddle) but unable to make it Round-Robin.


Solution

  • The main issue with your approach is that you are moving the container instead of its children. In order to achieve a carousel the children will have to be shuffled while off screen to their appropriate location in the queue.

    I have modified your jsfiddle with an example solution. http://jsfiddle.net/HZRSZ/4/

    The javascript would look something like this:

    $('#scroll-left').click(function() {
        $('.inner').first()  //select the first child
    
            //animate its movement left by using the left margin
            .animate({'margin-left':'-=100px'}, function() {
    
                //then once the item is off screen move it to the other side
                //of the list and reset its margin
                $(this).appendTo('.wrapper').css('margin-left', '');
            });
    });
    

    and the movement to the right is the same as left just reversed

    $('#scroll-right').click(function() {
        $('.inner').last()
            .css('margin-left', '-=100')
            .prependTo('.wrapper')
            .animate({'margin-left':'+=100'});
    });