D3 and UI animations

by Andreas Koller

When it comes to JavaScript libraries for animations, we’re spoilt for choice these days. I recently tried D3’s animation capabilities, which were built to enhance your data visualisations with transitions, and prototyped animated UI elements with it.

The simplest way to animate properties of DOM elements (say, we want to fade text color on mouseover) is to use CSS Transitions. They are defined directly in CSS and work well across browsers. We could also think of specifying keyframed animations in CSS, and triggering them with JavaScript. However, CSS animations lack convenience: while we can trigger, restart and pause/play the animations by changing the CSS dynamically, we can’t create or modify them in a very practical way. That’s where many JavaScript libraries like TweenJS, tween.js (yes, same name), jQuery’s animate, Raphaël and countless more come for help. They all support tweening with easing curves. D3 offers its transition operator to animate the properties of DOM elements — I’d recommend Jerome Cuckier’s tutorial to get an introduction to this topic.

While D3 might not have been built exactly for this purpose, it is also possible to create UI animations with it. Let’s start with a simple hover effect on a text:

‚Text Hover Effect‘. Mouseover effect on a text, changing its color and font size. Built with D3. See source code.

To animate the fill color an object on mouseover, which is a simple hover effect, use the transition() operator of D3:
.text(‚Touch me‘)
.attr(‚x‘, width/2)
.attr(‚y‘, height/2)
.attr(‚font-size‘, 20)
.attr(‚fill‘, ‚#333‘)
.style(‚text-anchor‘, ‚middle‘)
.on(‚mouseover‘, function(d,i) {
.attr(‚font-size‘, 32)
.attr(‚fill‘, ‚#F00‘);
.on(‚mouseout‘, function(d,i) {
.attr(‚font-size‘, 20)
.attr(‚fill‘, ‚#333‘);
Here we can see that it’s also possible to animate several properties (in this case font-size and fill color) at once. It’s much more complicated than a simple :hover CSS rule, but it offers so many possibilities to build more elaborate mouseover effects:

‚Button mouseover transitions‘. Button mouseover animations with d3 transitions, which offer much more possibilities than CSS animations. Bonus points for knowing why I selected these six countries for this demo! Built with D3. See source code.

I took it a little further and sketched a folding horizontal menu, which animates smoothly:

‚Folding Horizontal Menu II‘. Menu items unfold on mouseover and move on click. Activate slow transitions by pressing shift key. Built with D3. See source code.

The source codes of all examples are available on bl.ocks.org. These experiments were done during my research residency at CIID.

Schreib einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind markiert *