user2265754
user2265754

Reputation: 79

d3.js appending text when there is already text on the page

I'm trying to append some text to text which is already on the page. The first time I do it, it works. The second time I tried it, I had trouble until I found this: http://knowledgestockpile.blogspot.com/2012/01/understanding-selectall-data-enter.html

Once I added a key function, it worked for all entries but the first. How do I get the first to show up?

var dataset=[{"x":0, "y":2},{"x":1, "y":2},{"x":2, "y":2},{"x":3, "y":2}];
  vis.selectAll("text")
     .data(dataset)
     .enter()
     .append("text")
     .text(function(d,i) {return d.x;})
     .attr("text-anchor", "middle")
     .attr("x", function(d, i) {return scaleX(d.x);})
     .attr("y", function(d) {return scaleY(-5) ;})
     .attr("font-family", "sans-serif")
     .attr("font-size", "11px")
     .attr("fill", "black");

  vis.selectAll("text")
     .data(dataset,function(d){return d;})
     .enter()
     .append("text")
     .text(function(d,i) {return d.x;})
     .attr("text-anchor", "middle")
     .attr("x", function(d, i) {return scaleX(d.x);})
     .attr("y", function(d) {return scaleY(20) ;})
     .attr("font-family", "sans-serif")
     .attr("font-size", "11px")
     .attr("fill", "black");

Here is the fiddle: http://jsfiddle.net/tvinci/hbASc/2/

Upvotes: 0

Views: 454

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109232

By selecting the text and then calling data(), you're telling d3 to match the new elements with existing elements. When you do this, the intention is usually to update existing elements instead of simply adding all of them as new ones.

If what you want to do is add the text twice, you can assign different classes to the text in both selections such that the .enter() selection will contain all the elements in both cases. The code would be something like

vis.selectAll("text.one")
   .data(dataset)
   .enter()
   .append("text")
   .attr("class", "one")
   ...

vis.selectAll("text.two")
   .data(dataset)
   .enter()
   .append("text")
   .attr("class", "two")
   ...

If you want to update the existing text, remove the .enter() in the second call chain. It also won't be necessary to pass in a key function in this case.

Upvotes: 0

Related Questions