Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a dynamic list of DIVs with D3

I have been using D3 to create fancy animated charts, and the examples are great. However, I'm trying to do something seemingly a lot more basic, and having trouble - binding data to a simple list of DIVs.

I set up enter() to initialize elements at opacity 0, transition() to fade them in, and exit() to fade them out and remove them. enter() and exit() seem to be working fine - however, when an update contains an existing element already in the list, it seems to get partially removed - the containing DIV remains, but the contents disappear. I can't understand why the contents of the element would get changed in 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 set up a jsFiddle here demonstrating the issue.

like image 981
Tom Avatar asked Jan 21 '13 12:01

Tom


1 Answers

The problem is that you're selecting the divs you created, but create more than one div per data element. When updating, d3 tries to match the data to the nested divs. As you're already assigning a special class to the top-level divs, the fix is very simple. Replace

.selectAll('div')

with

.selectAll('.tweetdiv')
like image 158
Lars Kotthoff Avatar answered Sep 29 '22 12:09

Lars Kotthoff