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.
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(); });
});
}
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(); });
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With