JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
</body>
CSS
body {
border: 1px solid white;
margin: 0 1px;
}
text {
font: 24px sans-serif;
}
.enter {
fill: green;
}
.update {
fill: grey;
}
.exit {
fill: brown;
}
JavaScript
// this example is based on General Update Pattern, III by Mike Bostock
// you can find it here: http://bl.ocks.org/mbostock/3808234
var names = ['Sarah', 'Maria', 'Marc', 'Robert', 'Sam', 'Mike', 'Nora'];
var width = 650,
height = 100;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(15," + (height / 2) + ")");
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")
.transition()
.duration(750)
.attr("x", function (d, i) {
return i * 90;
});
// ENTER
// Create new elements as needed.
text.enter().append("text")
.attr("class", "enter")
.attr("dy", ".35em")
.attr("y", -60)
.attr("x", function (d, i) {
return i * 90;
})
.style("fill-opacity", 1e-6)
.text(function (d) {
return d;
})
.transition()
.duration(750)
.attr("y", 0)
.style("fill-opacity", 1);
// EXIT
// Remove old elements as needed.
text.exit()
.attr("class", "exit")
.transition()
.duration(750)
.attr("y", 60)
.style("fill-opacity", 1e-6)
.remove();
}
// The initial display.
update(names);
setInterval(function () {
update(shuffle(names)
.slice(0, 3 + Math.floor(Math.random() * 4.9))
.sort());
}, 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;
}