Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3.js: run a transition continuously?

How can I run a transition continuously in D3.js?

For example, say I want to change the body colour from red to blue and back again, continuously (I don't, that would be horrendous, but go with it).

This is how I would do it once:

d3.select("body").transition().duration(1000).style("background-color", "red");

How would I do it continuously?

The closest examples I have seen use d3.timer, but I am not sure if there is a better way to do it.

like image 680
Richard Avatar asked Jun 15 '13 20:06

Richard


2 Answers

You can use transition.each() and the "end" event. The code would look something like the following.

function myTrans() {
    d3.select("body").transition().duration(1000).style("background-color", "red")
      .each("end", function() {
        d3.select(this).transition().duration(1000).style("background-color", "blue")
          .each("end", function() { myTrans(); });
      });
}
like image 165
Lars Kotthoff Avatar answered Nov 05 '22 13:11

Lars Kotthoff


For D3 version 4 you have to use .on instead of .each (based on Lars answer):

function myTrans() {
    d3.select("body").transition().duration(1000).style("background-color", "red")
      .on("end", function() {
        d3.select(this).transition().duration(1000).style("background-color", "blue")
          .on("end", function() { myTrans(); });
      });
}
like image 1
Json Avatar answered Nov 05 '22 11:11

Json