adamK
adamK

Reputation: 3889

jquery animation of circular list

I have a vertical list of li elements that I want to rotate such that it appears as it is on a roller (like icons on a slot machine or numbers on a combination lock). I can create this by simply adding something like:

$('#list li:first').before($('#list li:last'));

Problem is sometimes the list is exactly the number of visible elements in length and what I would like to retain is the last element sliding off the bottom and concurrently sliding onto the top to create the look of a circular list. One thought was to duplicate the list elements if its length was less than the visible length and animating the margin-top property of each li element to slide down but then I have duplicates of each list element, is there a better way?

Any help would be appreciated.

Edit: Rotation function based on Alex Ball's response below.

function rotate(direction){
    var firstElem = $('#list ul li:first');
    var lastElem = $('#list ul li:last');
    var elemHeight =  firstElem.height();

    if(direction == 'down') {
        firstElem.animate({'marginTop': '+=' + elemHeight + 'px'}, 500, 'linear', function(){
            $(this).css({'margin-top':0}).before(lastElem);         
        });
    }

    if(direction == 'up') {
        firstElem.animate({'marginTop': '-=' + elemHeight + 'px'}, 500, 'linear', function(){
            lastElem.after($(this));
            $(this).css({'margin-top':0});
        });
    }
}

Upvotes: 1

Views: 1199

Answers (1)

Alex Ball
Alex Ball

Reputation: 4474

this is an example (I've used the idea of slot Machine because is fanny)

I started with some div container and list (li) of images, but the idea is valid for other types.

the rotete JS:

function rotate(id, n){

    console.log(id);    

     $('#'+id+' ul li:first').animate({'margin-top': '-='+$(this).height()+'px'}, 400, 'linear', function(){

          $(this).css({'margin-top':0}).parent().append($(this));

          i++;

          console.log('id: '+id+' i: '+i+' n: '+n);

          if(i < n) rotate(id, n);

     });

}

See in action FIDDLE

Upvotes: 1

Related Questions