update enter

https://bl.ocks.org/mbostock/1134768

by Justin Maat

HTML

<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<style>

text {
  font: bold 48px monospace;
}

.enter {
  fill: green;
}

.update {
  fill: #333;
}

</style>
<button id="hello">Hello</button>

</button>
<svg width="960" height="500"></svg>

CSS

.axis text {
  font: 10px sans-serif;
}

.axis line,
.axis path {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.axis--x path {
  display: none;
}

JavaScript

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

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

function update(data) {

console.log('new data ' + data);

  g.selectAll("text")
  .exit().remove()
//    .data(data, function(d) { return d;})
    
    ;
    
  // DATA JOIN
  // Join new data with old elements, if any.
  var text = g.selectAll("text")
    .data(data, function(d) { 
      console.log("d: " + d);
      return d;
  });
  
  // UPDATE
  // Update old elements as needed.
  text.attr("class", "update");

  // ENTER
  // Create new elements as needed.
  //
  // ENTER + UPDATE
  // After merging the entered elements with the update selection,
  // apply operations to both.
text.enter().append("text")
      .attr("class", "enter")
      .attr("x", function(d, i) { return i * 32; })
      .attr("dy", ".35em")
            .text(function(d) { return d; });  //why is merge required here ?

//   c.merge(text)


  // EXIT
  // Remove old elements as needed.
  //text.exit().remove();

}

// The initial display.
update(alphabet);

// Grab a random sample of letters from the alphabet, in alphabetical order.
$("#hello").click(function() {
//var d = d3.shuffle(alphabet)
//      .slice(0, Math.floor(Math.random() * 26))
//      .sort()
//      console.log(d)
update(['1', '2', '3', '4']);
      
});