Little animation with JQuery

Hey there ! I’m trying to make a animation with this code:

 $(".MyClass").each(function(index) {
                setTimeout($(this).fadeIn("slow"), 1000);
 });

The idea was to wait a second then execute the function for each element in the JQuery object, but all the elements are animated in the same time. I managed to get it to work doing this:

    var lenght = 0;
    var index = 0;

    $(".MyClass").each(function(index) {
        $(this).addClass("MyClass-"+index);
        length++;
    });

    var id = setInterval(function() {
        $(".MyClass-"+index).fadeIn(1000);
        index++;
        stopInterval();
    }, 1000);

    function stopInterval() {
        if (index > length) {
            clearInterval(id);
        }
    }

But I’m still want to know why the first code didn’t work.

Try this maybe

 $(".MyClass").each(function(index, value) {
     setTimeout(function (v) {$(v).fadeIn("slow") }, 1000, value);
 });

Didn’t work :frowning: They animated at the same time.

You can multiply the index with the fadeIn time which will animate one after the other.

$(".MyClass").each(function (k,v) {
    $(v).fadeIn(k*1000);
});

jsfiddle demo

2 Likes

Thanks ! That’s really cool, I would nerver come up with it myself !

1 Like