I need to make a FadeOut method (similar to jQuery) using D3.js. What I need to do is to set the opacity to 0 using transition()
.
d3.select("#myid").transition().style("opacity", "0");
The problem is that I need a callback to realize when the transition has finished. How can I implement a callback?
Now, in d3 v4.0, there is a facility for explicitly attaching event handlers to transitions:
https://github.com/d3/d3-transition#transition_on
To execute code when a transition has completed, all you need is:
Mike Bostock's solution for v3 with a small update:
You want to listen for the "end" event of the transition.
From the documentation for
transition.each([type],listener)
:See this forum thread on the topic for more details.
Finally, note that if you just want to remove the elements after they have faded out (after the transition has finished), you can use
transition.remove()
.Mike Bostock's solution improved by kashesandr + passing arguments to the callback function:
A slightly different approach that works also when there are many transitions with many elements each running simultaneously:
Actually there's one more way to do this using timers.