Skip to content

Instantly share code, notes, and snippets.

@Andrew-Reid
Last active July 4, 2018 20:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Andrew-Reid/ae14de2768b5d07d9fbf554ae02caf02 to your computer and use it in GitHub Desktop.
Save Andrew-Reid/ae14de2768b5d07d9fbf554ae02caf02 to your computer and use it in GitHub Desktop.
Force Transitions to End State and Trigger End Event (v3)

Based on a request to modify this block to work with d3v3. The original block is based on this Stack Overflow answer and is intended to create a method to flush transitions on a selection.

The bl.ock adds a method to d3.selection() that allows a user to force the transition to its end state:

  • values transitioned move to the final interpolated values, and
  • the transition end event triggers.

Circles start are drawn intially as black. On the beginning of the transition, after the delay (the transition is initalized prior to the delay start) the nodes turn green and begin to transition across the screen. When the transition ends, the nodes turn blue.

Clicking on the nodes forces the transition to its end point while triggering the end event (nodes turn blue). I've added a second transition on click to show those nodes that have been clicked, this transition reduces node radii.

<script src="https://d3js.org/d3.v3.js"></script>
<body>
<script>
d3.selection.prototype.finish = function() {
// check if there is a transition to finish:
if (this.node().__transition__) {
// get each transition in progress:
var transitions = this.node().__transition__;
// for each potential transition:
var keys = Object.keys(transitions);
keys.forEach(function(d,i) {
var t = transitions[d];
// confirm we have a transition:
if(t && t.timer) {
// get the current callback and its name:
var f = t.timer.c;
var name = f.name;
// if the transition is in progress, use duration:
if(name == "tick") {
t.timer.c(f(t.duration));
t.timer.t = t.duration;
}
// otherwise set the time:
else {
t.timer.c(f(Infinity));
t.timer.t = Infinity;
}
}
})
}
return this;
}
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500);
var circle = svg.selectAll("circle")
.data([1,2,3,4,5,6,7,8])
.enter()
.append("circle")
.attr("cx",50)
.attr("cy",function(d) { return d * 50 })
.attr("r",20)
.on("click", function() { d3.select(this).finish().transition().attr("r",10).duration(1000); })
circle
.transition()
.delay(function(d) { return d * 500; })
.duration(function(d) { return d * 5000; })
.attr("cx", 460)
.each("start", function(d) {
d3.select(this).attr("fill","olive");
})
.each("end", function(d) {
d3.select(this).attr("fill","steelblue");
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment