Skip to content

Instantly share code, notes, and snippets.

@1wheel
Forked from mbostock/.block
Created November 6, 2013 04:14
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 1wheel/7330771 to your computer and use it in GitHub Desktop.
Save 1wheel/7330771 to your computer and use it in GitHub Desktop.

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

<!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="http://d3js.org/d3.v2.min.js?2.10.1"></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(shuffle(alphabet)
.slice(0, Math.floor(Math.random() * 26))
.sort());
}, 1500);
// Shuffles the input array.
function shuffle(array) {
var m = array.length, t, i;
while (m) {
i = Math.floor(Math.random() * m--);
t = array[m], array[m] = array[i], array[i] = t;
}
return array;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment