3gwebtrain
3gwebtrain

Reputation: 15293

How to add delay on animation by calculating `index` value in d3.js?

I have 2 elements in a group and I am selecting groups using selectAll method. But I want to add some delay on it's child elements on transition. What is the correct approach for this?

My try is not working at all:

var fadeHandler = function () {
    d3.selectAll('.subAppGroup') //parent group
        .each(function (d,i) {
            console.log("hi", i); //i am getting index here.
        })
        .transition()
        .delay((1000*1+=1)) //how to delay?
        .duration(500)
        .select('.subAppPath') //first child
        .style('opacity', 1);

    d3.selectAll('.subAppGroup')
        .transition()
        .delay((1000*1+=i)) //both not working
        .duration(500)
        .select('.subAppGroupDetail') //second child

        .style('opacity', 1);

}

fadeHandler();

Upvotes: 1

Views: 399

Answers (1)

lhoworko
lhoworko

Reputation: 1191

You just need to put the logic inside a function. i will be the index of the item in the array. In the example below element 0 will delay 0ms, element 1 100ms, and so on.

...
.delay(function(d, i) {
    return i * 100; // Or whatever you want the delay to be.
})
...

https://github.com/mbostock/d3/wiki/Transitions#delay

Edit: To answer your comment below, try this. I think this will work but it's hard to say without knowing what your data looks like.

var fadeHandler = function () {
    d3.selectAll('.subAppGroup .subAppPath, .subAppGroup .subAppGroupDetail')
        .transition()
        .delay(function(d, i) {
            return i * 100;
        })
        .duration(500)
        .style('opacity', 1);
}

fadeHandler();

Upvotes: 1

Related Questions