Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding CSS animation with delay to each list item [duplicate]

I'm trying to write some jquery that will go through a specified unordered list / dom element and assign a CSS (animation) class to each list item / child. I also want to make an adjustable delay time between the .addClass.

Everything I've tried has failed miserably.

For example:

<ul>
   <li>Item 1</li>
   <li>Item 2</li>
   <li>Item 3</li>
   <li>Item 4</li>
</ul>

Becomes:

<ul>
   <li class="animation">Item 1</li>
     (50ms delay)
   <li class="animation">Item 2</li>
     (50ms delay)
   <li class="animation">Item 3</li>
     (50ms delay)
   <li class="animation">Item 4</li>
     (50ms delay)
</ul>

Any thoughts?

like image 991
apttap Avatar asked Jun 22 '12 22:06

apttap


3 Answers

This here works:

$('ul li').each(function(i){
    var t = $(this);
    setTimeout(function(){ t.addClass('animation'); }, (i+1) * 50);
});

http://jsfiddle.net/GCHSW/1/

like image 124
Adam Merrifield Avatar answered Oct 20 '22 10:10

Adam Merrifield


Consider this:

HTML:

<ul id="myList">
   <li>Item 1</li>
   <li>Item 2</li>
   <li>Item 3</li>
   <li>Item 4</li>
</ul>

Javascript:

$("#myList li").each(function(i, li) {
    var $list = $(this).closest('ul');
    $list.queue(function() {
        $(li).addClass('animation');
        $list.dequeue();
    }).delay(50);
});

See fiddle: http://jsfiddle.net/DZPn7/2/

Although this is neither concise nor efficient, it is a jQuery purist's solution.

like image 21
Beetroot-Beetroot Avatar answered Oct 20 '22 08:10

Beetroot-Beetroot


I have 2 ways for animations (with jQuery and CSS3 Transitions + .addClass ).

So, You can try jQuery for example:

$('#myList li').each(function(i){
   $(this).delay(50*i).animate({opacity: 1},250);
});

and using CSS3 Transitions:

$('#myList li').not('.animation').each(function(i){
    setTimeout(function(){
       $('#myList li').eq(i).addClass('animation');
    },50*i);
});

Enjoy!

like image 23
Tusko Trush Avatar answered Oct 20 '22 10:10

Tusko Trush