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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With