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, but these graphical features can be used in other ways as well. The toolkit usually reached for in this space is jQuery UI, which carries a lot of extra baggage — especially if you’re already using D3.js for charts.

One jQuery UI feature that’s also present in D3.js is the ability to set styles, transition them into other styles, and tie that transition to a timeout. My D3.js Color Transitions Pen demonstrates this effect. The important part is the JavaScript:


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 with it.