Search code examples
d3.jstransitionslide

D3: use transition .attr('x') to horizontally slide <text> elements


I want to

  1. display some text one after another
  2. after each of the text is displayed, I would like to slide them horizontally from the left side of the page to the right side of the page: so I would like to change the texts' x= 10 to x= 500.

I am able to make step 1) but not 2). Here is my script:

var textall =["one", "two", "three"]
  var number = -1
    d3.select('svg')
        .transition()
            .duration(0)
            .delay(0)
            .on("start", function addtext() {
            number+=1;
            if (number < textall.length){
                d3.select('svg').append('g').append("text")
                    .attr("class", "one")
                    .attr('x', 10)
                    .attr('y', function(d,i) {return (number+1)*30; })
                    .text(textall[number])
                    .attr("font-family", "sans-serif")
                    .attr("font-size", "20px")
                    .attr("fill", "black")
                    .transition()
                        .duration(0)
                        .delay(2000)
                        .on("start", addtext);
                        }
            <!-- }; -->
        });

    d3.selectAll(".one")
        .transition()
            .duration(1000)
            .delay(6000)
            .attr('x', 90)

On jsfiddle


Solution

  • Updated Fiddle I have updated your fiddle, not with the end result but with enough that you can fill in the exact values. Basically I added and .on("end") function that moves the text after they have been added. Further tweaking can happen to improve the aesthetic.