Introduction to D3.js Introduction to D3.js

Animate with Transitions Exercise

Check out a free preview of the full Introduction to D3.js course:
The "Animate with Transitions Exercise" Lesson is part of the full, Introduction to D3.js course featured in this preview video. Here's what you'd learn in this lesson:

Students are instructed to add transitions to animate the bar chart started in the previous lesson so that entering bars animate up, updating bars animate to their new positions, and exiting bars animate back down.

Get Unlimited Access Now

Transcript from the "Animate with Transitions Exercise" Lesson

[00:00:00]
>> So we're going to take that simple bar chart that we've been working on, and we're going to have it animate. And when we animate on update what we want is, for all of the bars that we've created to animate up, so what's gonna happen is we're going to use the y and height attributes so that it will look like the bars are rising.

[00:00:29] And then then for the updating bars, the bars that have remained in the DOM, we're going to animate to their new positions. So this is we're going to be updating x, and this is kind of what I mentioned earlier about how, with the animations, we're going to see the shuffling of those bars from the old data array to the new data array.

[00:00:59] So for the updating bars, we're going to animate to their new positions, with the x position. And finally for any bars that are exiting and are going to be removed, we should animate them back down. And so again we're going to be setting the y and height attributes, to make that happen.

[00:01:25] So we're going to put our cone right here. And everything outside it is kind of just set up to have this but the important thing to know is that we've actually put our update code and also our animation code in this function called update bars, that gets called every time the button is clicked.

[00:01:51] And this is how we might if we're working in like a index HTML file, or if we're building something out in our local dev environment, this is how we'll most likely do the updating, where we put our update code into a function, and we call it from outside.

[00:02:14] And the end result should look something like this. And so, if you notice this bar just animated from over here to over here, because in state a, it was probably second or third index in the array and now that looks like it's the sixth element in the array.

[00:02:38] And so if you keep doing that, This is what, What our end result should look like. And another note is when you're doing the code, try doing the update code with the new way with .join. And the hint is that because we're going to have to animate specific enter and exit selections, that we want to use dot join and kind of pass in those three functions, to get the effect that we want.