user3441959
user3441959

Reputation: 135

Updating text elements in d3.js

Is it possible with d3.js to remove text elements one by one and update them straight away when the element is removed? So for example: there is an initial string with 0's shown in the image, then remove the first text element and then update it straight away and so on.

https://lh4.googleusercontent.com/-BxbMS_JqyO0/UzgsTEC_SgI/AAAAAAAAAAw/tVs3ADJCGJg/s3200/Screen+Shot+2014-03-30+at+15.37.35.png

I have been stuck on this for a while, I can remove all the elements at once but not one by one. Can someone please point me in the right direction? Is there a tutorial which I can look at?

Below is example code:

     var stepData = [ [[0,0,0,0,0,0,0],[0,1,1,1,1,1,1],[0,1,2,2,2,2,2],[0,1,2,2,2,2,2]], [[0,0,0,0,0,0,0],[0,0,0,0,0,1,1],[0,1,1,1,1,1,1],[0,1,1,2,2,2,2]] ];
     svgWidth = 600;
     svgHeight = 1000;
     delay = 1000;
     svg = d3.select("body")
             .append("svg")
             .attr("width", svgWidth)
             .attr("height", svgHeight);

svg.append("g")
   .attr("class", "data")
   .selectAll("g")                  
   .data(stepData[0])
   .enter()
   .append("g")
   .selectAll("text")
   .data( function(d,i,j){ 
       return d; 
    })
   .enter()
   .append("text")
   .text( function(d,i,j) { 
     if ( j === 0) {
         return d; 
     }
   })
   .attr("x", function(d,i,j) { return (i * 50) + 50; })
   .attr("y", function(d,i,j) { return (j * 50) + 50; })
   .attr("text-anchor", "middle")
   .attr("fill", "black"); 

svg.select(".data")
   .transition()
   .delay(function(d, i, j) {       
           return i * delay + 1000; 
    })
   .remove();

Thank you.

Upvotes: 1

Views: 3266

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109242

The problem is that you're selecting the g element containing everything and removing that. Your selection contains only a single element and therefore everything is removed at once. If you instead select the text elements, it works fine.

Complete demo here.

Upvotes: 2

Related Questions