D3: Can I have an svg transition based on items in a list?

Viewed 66

I would like to take a list...

var data = [100, 200, 300] // arbitrarily long

... and transition an element across the screen based on each list item. For example, I would like to send a dot first to [100,100], [200,100], [300,100]. Is there a way to do this with data joining?

Right now, I have have a solution that works, but it works in what seems to be a very un-D3-ish way: using a counter to iterate through a list, and using no data-binding. Excluding the CSS, here's the code:

<svg>
  <circle/>
</svg>


<script>

var data = [100,200,300]

var circle = d3.selectAll("circle")
    .attr("r",20)
    .attr("cy",100)
    .attr("cx",0)

var count = 0

repeat()

function repeat() {
  var run = circle
    .transition()
    .duration(1000)
    .attr("cx", function (d) {return data[count]});

    count++

  if (count < data.length){
    run
      .each("end", repeat);
  }   
}

</script>

Shouldn't there be a way to do this with data binding? I'd love to do this the right way, but for now this is all I can figure out just to make it work.

2 Answers
Related