Add delayed CSS animations to each list item

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

Everything I tried failed.

For instance:

<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?

+5
source share
4 answers

It works here:

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

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

+14
source

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 the script: http://jsfiddle.net/DZPn7/2/

Although it is neither concise nor effective, it is a jQuery purist solution.

+1
source

2 ( jQuery CSS3 + .addClass).

, jQuery, :

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

CSS3:

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

!

+1
source

Despite the fact that the above answer fits the scenario <ul>and <li>it will not work very well for a more complex situation. To really dial this, functionality must be wrapped in a function that accepts the target element and delays input. The function will then take this element and set a timeout with a delay for ... sigh, this is too important, I just have to encode it:

function applyAnimation(element, delay){
 setTimeout(function(){ $(element).addClass('animation'); }, delay);
 var children = document.getElementById(id).children;
 for( var i = 0; i < children.length; i++){
  applyAnimation(children[i],(2+i) * delay);//2+i:0 fails, 1 would be parent, 2 is child
 }
} 
0
source

All Articles