So I want to add a class to each element in a list(specifically the <a>
in the list items), but one at a time. I am doing this because the <a>
have a CSS transition on them and I want to have them animate one at a time. So item1 animates, then item2 animates, then item3 animates... Here is what I could attempt to come up with so far.
html:
<ul>
<li><a>item1</a></li>
<li><a>item2</a></li>
<li><a>item3</a></li>
</ul>
jQuery/js:
animateItems();
function animateItems(){
$('ul li a').each(function() {
$(this).addClass('animate'); //This doesn't run one at a time
});
}
I feel like this is leading in the direction of recursion, but not sure really.
update: I just realized that this may be harder than i thought because jQuery needs to know about the css transition time doesnt it? Is there a way to add the classes with a setTimeout() until it begins the next addClass()? Does each() create an array or jQuery object that I can iterate through?
The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.
To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so: document. getElementById("MyElement").
You could use the setTimeout
function:
$('ul li a').each(function(i, el) {
setTimeout(function() {
$(el).addClass('...');
}, i * 1000);
});
The above code assumes that the CSS animation duration is 1s. You can change it accordingly!
And a note: this
in the context of the setTimeout
callback function doesn't refer to the current element. You should either cache the this
object of the each
callback or use the second parameter of the each
callback which refers to the current element in the set.
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