Skip to content

Instantly share code, notes, and snippets.


rettal/D3 States

Last active Aug 29, 2015
What would you like to do?
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
Code example explaining the enter, update and exit states in D3.
The 3 states basically define the actions that occur when data is added to a selection of elements.
Say if we were selecting data from a database where we had to perform a search with a query string,
each time we ran query the number of rows returned could be more, less, or could be the same but
contain different data, these in essence are the 3 states. more = enter, less = exit, same = update.
The following function illustrates the 3 states by running a function every 3 seconds
that changes (randomly) the data "joined" to the elements in the dom.
The elements in the dom are svg <circle> elements to help illustrate the effect.
setInterval(function() {
var cnt = getRandomInt(3, 10), data = [];
for (var i = 0; i < cnt; i++) {
data.push({"x": Math.random() * (320 - 10) + 10, "y": Math.random() * (320 - 10) + 10});
var svg ="svg");
var circle = svg.selectAll("circle")
.attr("r", 2.5);
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}, 3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.