Creating a Dynamic DIV List with D3

I use D3 to create fantastic animated diagrams, and the examples are great. However, I am trying to do something that would seem to be much more thorough and have problems binding data to a simple DIV list.

I set enter() to initialize elements with opacity 0, transition() to fade them, and exit() to fade and delete them. enter() and exit() seem to work fine - however, when the update contains an already existing item that appears to be partially deleted - the containing DIV remains, but the contents disappear. I cannot understand why the content of the element will be changed this way.

My code is as follows:

 var data = [...]; sorted = data.sort(function(a, b) { return d3.descending(a.id, b.id); }); var tweet = tweetsBox .selectAll('div') .data(sorted, function(d) { return d.id; }); var enterDiv = tweet.enter() .append("div") .attr("class", "tweetdiv") .style("opacity", 0); enterDiv.append("div") .attr("class", "username") .text(function(d) { return "@" + d.username }); enterDiv.append("div") .attr("class", "displayname") .text(function(d) { return d.displayname }); enterDiv.append("div") .attr("class", "date") .text(function(d) { return d.date }); enterDiv.append("div") .attr("class", "text") .text(function(d) { return d.text }); tweet.transition() .delay(200) .style("opacity", 1); tweet.exit() .transition() .duration(200) .style("opacity", 0) .remove(); 

I also created jsFiddle here demonstrating the problem.

+6
source share
1 answer

The problem is that you select the created div , but create more than one div for each data item. When updating, d3 tries to match data with nested div s. Since you already assign a special class to the top level div s, the fix is ​​very simple. Replace

 .selectAll('div') 

with

 .selectAll('.tweetdiv') 
+6
source

All Articles