1st d3 experiments
using enter, append
by hrabinowitz
HTML
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 20 20" preserveAspectRatio="xMinYMin meet" height="50"></svg>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
<p>Paragraph 5</p>
<p>Paragraph 6</p>
<p>Paragraph 7</p>
<p>Paragraph 8</p>
<p>Paragraph 9</p>
<p class="cl1">Paragraph cl1 1</p>
<p class="cl1">Paragraph cl1 2</p>
<p class="cl1">Paragraph cl1 1</p>
<p class="cl1">Paragraph cl1 2</p>
<p class="cl1">Paragraph cl1 1</p>
<p class="cl1">Paragraph cl1 2</p>
<p class="cl1">Paragraph cl1 1</p>
<p class="cl1">Paragraph cl1 2</p>
<p class="cl1">Paragraph cl1 1</p>
<p class="cl1">Paragraph cl1 2</p>
CSS
circle {
fill: "red";
}
JavaScript
d3.selectAll("p").style("color", function() {
return "hsl(" + Math.random() * 360 + ", 50%, 40%)";
});
d3.selectAll("p.cl1").style("color", function(d, i) {
return i % 2 ? "#222" : "#555";
}).style("background-color", "gray");
d3.selectAll("p")
.data([4, 8, 15, 16, 23, 42])
.style("font-size", function(d) { return d + "px"; });
d3.selectAll("p.cl1")
.data([4, 8, 15, 16, 23, 42])
.style("padding-left", function(d) { return d + "px"; });
var cl1Ps = d3.select("body").selectAll("p.cl1")
.data([4, 8, 15, 16, 23, 42, 5, 9, 11, 21, 44, 12, 6, 5])
.text(function (d) {
return "original node with data=" + d;
});
cl1Ps.enter().append("p")
.text(function(d) {
return "new node with data=" + d + "!";
});
var myData = [{x:5, y:5}, {x:7, y:7}, {x:10, y:10}];
var svg = d3.select("svg");
var circles = svg.selectAll("circle")
.data(myData)
.enter().append("circle")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", function(d) { return Math.sqrt(d.x); });
circles.transition().duration(1000).style("fill", "steelblue");
d3.select("p").transition()
.duration(1000)
.style("background-color", "black");
var selection = d3.select("body");