Reputation: 960
I have created some simple CSS flip cards and used setInterval to have them flip every 2 seconds.
setInterval(function()
{
$('.flip-card').toggleClass('flip-card-flipped');
}, 2000);
That works fine, but every card flips at the same time and I would like to have them flip one after the other. So I have been trying to use the .each function but the cards do not flip at all when I use .each.
$(".flip-card").each(function(i, obj)
{
setInterval(function()
{
obj.toggleClass('flip-card-flipped');
},(i * 1000) + 2000);
});
In this example, the flip animation takes one second, so the above code attempts to get the index of the class and multiply it by 1000 to get seconds to offset the interval by. so the first card will flip after (0 * 1000) + 2000, the next one will be (1 * 1000) + 2000 and so on, i.e. 2s, 3s, 4s....
Upvotes: 0
Views: 160
Reputation: 21364
It's not clear to me from reading the documentation, https://api.jquery.com/each/, how to use the obj
argument to the .each
function. In their examples they seem to recommend using this
instead.
In addition it seems that you want an offset, rather than increasing the interval for latter cards. The interval, as you said, should be 2s for all cards. The only difference should be when they start their flipping cycles if I understand correctly. If so then you want an offset.
$(".flip-card").each(function(i) {
setTimeout(() =>
setInterval(() => $(this).toggleClass('flip-card-flipped'), 2000),
i * 1000
);
});
Upvotes: 2