I am currently working on creating visualizations using D3
, and one challenge that I have encountered is the need to define a lot of styles within my code instead of in my CSS
where I would prefer them to be.
This necessity arises mainly to support transitions. I have observed that while it is possible to transition from a CSS-applied style to an inline one, reverting back to the original style becomes problematic. In order for transitions to work smoothly, all styles must be defined inline as demonstrated in the following example:
var svg = d3.select("svg");
var c1 = svg.append("circle")
.attr("class", "red")
.attr("r", 25)
.attr("cx", 50)
.attr("cy", 50);
var c2 = svg.append("circle")
.attr("r", 25)
.attr("cx", 250)
.attr("cy", 50)
.style("fill", "red");
svg.selectAll("circle")
.transition()
.delay(2000)
.duration(2000)
.style("fill", "blue");
c1.transition()
.delay(5000)
.duration(2000)
.style("fill", "");
c2.transition()
.delay(5000)
.duration(2000)
.style("fill", "red");
.red {
fill: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="500" height="500">
</svg>
The circle on the left abruptly changes back to red without transitioning, whereas the one on the right smoothly transitions back.
I am looking for a more elegant solution to transition the left circle back without needing to redefine the original color from CSS within my JavaScript code.
If anyone has any insights or suggestions on how this can be achieved gracefully, I would greatly appreciate it!