Skip to content

Instantly share code, notes, and snippets.

@ctiml
Forked from mbostock/.block
Last active November 10, 2015 14:19
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 ctiml/2f83b01e2576b02f68bc to your computer and use it in GitHub Desktop.
Save ctiml/2f83b01e2576b02f68bc to your computer and use it in GitHub Desktop.
09-General Update Pattern, II
<!DOCTYPE html>
<meta charset="utf-8">
<style>
text {
font: bold 48px monospace;
}
.enter {
fill: green;
}
.update {
fill: #333;
}
.remove {
fill: red;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
var a = "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 / 12) + ")");
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");
// ENTER
// Create new elements as needed.
text.enter().append("text")
.attr("class", "enter")
.attr("dy", ".35em")
.attr("y", 0)
.text(function(d) { return d; });
// ENTER + UPDATE
// Appending to the enter selection expands the update selection to include
// entering elements; so, operations on the update selection after appending to
// the enter selection will apply to both entering and updating nodes.
text.transition().attr("x", function(d, i) { return i * 32; })
.attr("y", 0);
// EXIT
// Remove old elements as needed.
text.exit().attr("class", "remove").transition().attr("y", function(d, i) { return parseInt(d3.select(this).attr("y")) + 45; });
}
// 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