Note: Please view the related Pen for this post: D3.js Color Transitions.

D3 Logo
D3 Logo

D3.js is often praised for its chart drawing capabilities; however, these graphical features can be used in other ways as well. Usually the toolkit used for this sort of thing is jQuery UI; however, there is a lot of extra baggage that comes along with that, especially if you are already using D3.js for charts.

An example jQuery UI feature that is also present in D3.js is the ability to set styles, transition them into other styles, and tie that transition to a timeout event. My D3.js Color Transitions Pen illustrates this effect. The important part is this Javascript code:


function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
function transitionHeaderColors() {
  d3.selectAll("h1")
  .transition()
  .duration(3000)
  .style("background-color", function() {
    var r = getRandomInt(0, 150),
        g = getRandomInt(0, 150),
        b = getRandomInt(0, 150);
    return "rgb(" + [r, g, b].join(",") + ")";
  })
  .style("color", function() {
    var r = getRandomInt(0, 150),
        g = getRandomInt(0, 150),
        b = getRandomInt(0, 150);
    return "rgb(" + [r, g, b].join(",") + ")";
  });
  window.setTimeout(transitionHeaderColors, 3000);
}
transitionHeaderColors();

Simple and easy! Fork the Pen and have some fun if you’d like.