2/21/2014 - 9:44 AM


<!DOCTYPE html>
<meta charset="utf-8">

text {
  font: bold 48px monospace;

.enter {
  fill: green;

.update {
  fill: #333;

<script src="http://d3js.org/d3.v2.min.js?2.10.1"></script>

var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");

var width = 960,
    height = 500;

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
    .attr("transform", "translate(32," + (height / 2) + ")");

function update(data) {

  // Join new data with old elements, if any.
  var text = svg.selectAll("text")

  // Update old elements as needed.
  text.attr("class", "update");

  // ENTER
  // Create new elements as needed.
      .attr("class", "enter")
      .attr("x", function(d, i) { return i * 32; })
      .attr("dy", ".35em");

  // 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.text(function(d) { return d; });

  // EXIT
  // Remove old elements as needed.

// The initial display.

// Grab a random sample of letters from the alphabet, in alphabetical order.
setInterval(function() {
      .slice(0, Math.floor(Math.random() * 26))
}, 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;


This example demonstrates the general update pattern in D3, where a data-join is followed by operations on the enter, update and exit selections. Entering elements are shown in green, while updating elements are shown in black. Exiting elements are removed immediately, so they're invisible.

This example does not use a key function for the data-join, so entering elements are always added to the end: when the new data has more letters than the old data, new elements are entered to display the new letters. Likewise, exiting letters are always removed from the end when the new data has fewer letters than the old data.

Next: Key Functions