D3 General Update Pattern

var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
var width = 960;
var height = 500;
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(32," + (height / 2) + ")");
// The initial display.
update(alphabet);
setInterval(function() {
update(
d3
.shuffle(alphabet)
.slice(0, Math.floor(Math.random() * 26))
.sort()
);
}, 1500);
function update (data) {
// DATA JOIN
var text = svg
.selectAll("text")
.data(data);
// "UPDATE SELECTION"
text.attr("class", "update");
// "ENTER SELECTION"
text
.enter()
.append("text")
.attr("class", "enter")
.attr("x", function(d, i) { return i * 32; })
.attr("dy", ".35em");
// "ENTER + UPDATE SELECTION"
// I.E., THE NEW UPDATE SELECTION
text.text(function(d) { return d; });
// "EXIT SELECTION"
text.exit().remove();
}
// DATA JOIN
var text = svg
.selectAll("text")
.data(data);
// UPDATE SELECTION
text.attr("class", "update");
// "ENTER SELECTION"
text
.enter()
.append("text")
.attr("class", "enter")
.attr("x", function(d, i) { return i * 32; })
.attr("dy", ".35em");
// "ENTER + UPDATE SELECTION"
// I.E., THE NEW UPDATE SELECTION
text.text(function(d) { return d; });
// "EXIT SELECTION"
text.exit().remove();

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store