This video is available to students only

CSS transitions with a chart

We add CSS transitions to our histogram, animating changes as the bars change.

CSS transition with a chart#

In this example, the index.html is importing a CSS stylesheet (styles.css) and the chart.js file, which is an updated version of our histogram drawing code from Module 3.

The code should look mostly familiar, but you might notice a few changes. Don't worry about those changes at the moment — they're not important to our main mission.

Let's look inside that styles.css file. We can see that we have already set the basic styles for our bars (.bin rect), bar labels (.bin text), mean line (.mean), and x axis label (.x-axis-label).

Great! Now that we know the lay of the land, let's look at our example — we should see our histogram and a Change metric button.


When we click the button, our chart re-draws with the next metric, but the change is instantaneous.

instant change

Does this next metric have fewer bars than the previous one? Does our mean line move to the left or the right? These questions can be answered more easily if we transition gradually from one view to the other.

Let's add an animation whenever our bars update (.bin rect).

Note that this CSS transition will currently only work in the Chrome browser. This is because Chrome is the only browser that has implemented the part of the SVG 2 spec which allows height as a CSS property, letting us animate the transition.

Now when we update our metric, our bars shift slowly to one side while changing height — we can see that their width, height, x, and y values are animating. This may be fun to watch, but it doesn't really represent our mental model of bar charts. It would make more sense for the bars to change position instantaneously and animate any height differences. Let's only transition the height and y values.


This page is a preview of Fullstack D3 Masterclass

Start a new discussion. All notification go to the author.