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 (
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.
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 (
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
heightas 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
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