Skip to content

Instantly share code, notes, and snippets.

@jfsiii
Created June 2, 2016 20:02
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 jfsiii/963694ae9799d99f24a0e01646c68783 to your computer and use it in GitHub Desktop.
Save jfsiii/963694ae9799d99f24a0e01646c68783 to your computer and use it in GitHub Desktop.
General Update Pattern, III
license: gpl-3.0

By adding transitions, we can more easily follow the elements as they are entered, updated and exited. Separate transitions are defined for each of the three states.

Note that no transition is applied to the merged enter + update selection; this is because it would supersede the transition already scheduled on entering and updating elements. It's possible to schedule concurrent elements by using transition.transition or by setting transition.id, but it's simpler here to only transition the x-position on update; for entering elements, the x-position is assigned statically.

Want to read more? Try these tutorials:

See the D3 wiki for even more resources.

Previous: Key Functions

forked from mbostock's block: General Update Pattern, III

<!DOCTYPE html>
<meta charset="utf-8">
<style>
text {
font: bold 48px monospace;
}
.enter {
fill: green;
}
.update {
fill: #333;
}
.exit {
fill: brown;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
var width = 960,
height = 500;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(32," + (height / 2) + ")");
function update(data) {
// DATA JOIN
// Join new data with old elements, if any.
var text = svg.selectAll("text")
.data(data, function(d) { return d; });
// UPDATE
// Update old elements as needed.
text.attr("class", "update")
.transition()
.duration(750)
.attr("x", function(d, i) { return i * 32; });
// ENTER
// Create new elements as needed.
text.enter().append("text")
.attr("class", "enter")
.attr("dy", ".35em")
.attr("y", -60)
.attr("x", function(d, i) { return i * 32; })
.style("fill-opacity", 1e-6)
.text(function(d) { return d; })
.transition()
.duration(750)
.attr("y", 0)
.style("fill-opacity", 1);
// EXIT
// Remove old elements as needed.
text.exit()
.attr("class", "exit")
.transition()
.duration(750)
.attr("y", 60)
.style("fill-opacity", 1e-6)
.remove();
}
// The initial display.
update(alphabet);
// Grab a random sample of letters from the alphabet, in alphabetical order.
setInterval(function() {
update(d3.shuffle(alphabet)
.slice(0, Math.floor(Math.random() * 26))
.sort());
}, 1500);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment