This question already has an answer here:
-
How to make each <li> tag appear slowly one after the other
1 answer
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?
This here works:
$('ul li').each(function(i){
var t = $(this);
setTimeout(function(){ t.addClass('animation'); }, (i+1) * 50);
});
http://jsfiddle.net/GCHSW/1/
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.
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!
Although the answer above does a good job of approaching the <ul>
and <li>
scenario, it will not work very well for a more verbose situation. To really dial this in, the functionality should be wrapped in a function which accepts the target element and delay as an input. The function will then take that element, and set a timeout with the delay for ...sigh, this is too involved I should just code 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
}
}