Main content
Course: Computer programming - JavaScript and the web > Unit 6
Lesson 6: DOM animationWhat DOM animation technique should you use?
You've now seen three techniques that let you animate parts of your webpage:
window.setInterval
/setTimeout
, window.requestAnimationFrame
, and CSS animations/transitions.When you're considering what technique to use, you should consider these questions:
- Can it actually do what I want to do?
- How well does this technique perform? (Does it slow down the browser/computer?)
- How accurate does my timing need to be?
- Does it work in all the browsers that I want my webpage to work in?
When making webpages, we're very concerned about performance, so we like to consider that as the most important criteria. However, browser performance does change when new browsers come out, and mobile browsers can perform very differently from desktop browsers, so the technique that performs best today may not be the technique that performs best tomorrow. Currently, CSS animations/transitions are the most performant, then
requestAnimationFrame
, then setInterval
.However, CSS can't do everything. For example, to draw pixels and shapes in a
<canvas>
tag, you have to call functions like fillRect()
, you can't use CSS. You would need to use requestAnimationFrame
or setInterval
to call those functions periodicially instead. In fact, that's what we do here on Khan Academy, in our ProcessingJS environment. ProcessingJS is a JS library that writes out to a <canvas>
tag, and if you define a draw()
function in your code, then ProcessingJS uses setInterval
to call that draw()
function repeatedly based on the frameRate
.Sometimes, you want to call JavaScript functions periodically, but not because you want to animate something on the page. You might be polling a server for updates, like Twitter does when it updates its realtime feed. In that case, you can just use
setInterval
, and it doesn't matter that the timing isn't accurate, because you're only calling it every minute or so. That's what we do on Khan Academy on the help requests page, to continuously check for new help requests every 2 minutes.Of course, you should keep browser compatibility in mind. If you're writing code that needs to work in IE9, then you can't use
requestAnimationFrame
or CSS animations. You need to use a combination of techniques that work across the browsers, or find a library that does that for you, like Velocity.js.There is a lot more to learn about all of these techniques. Follow these links to learn more:
Bonus for Doctor Who fans: one of my favorite examples of the power of CSS3 animations is this animated TARDIS.
Want to join the conversation?
- When will Khan Academy have more lessons?(22 votes)
- Considering that this course just came out, and it was not long at all before that that the full HTML+CSS course came out, and before that content was added for SQL, and there were new lessons added for a different skill level or devices (using code "blocks" instead of typing). And then the other end of the spectrum was also covered, too, as the "Algorithms" course got added to the CompSci section. And if you go back much further, the JS content that exists now was being expanded-- a couple of times, I think.
I'd say the answer is to a question like that is: "Pretty darn often, all things considered!" since it seems to me like content gets added regularly. More than once a year seems pretty often to me, and it's been averaging way more than that!
What sort of lessons were you looking for? Was there something specific you were looking to learn?(29 votes)
- Question @Pamela: some HTML5 here. Is a full unit on HTML5 planned or in progress?(2 votes)
- Yes I sure it might stay The samme for years(1 vote)
- So this is how you'd animate something without ProcessingJS?
https://www.khanacademy.org/computer-programming/animation-wo-drawfunction/6226246389334016(2 votes)- I believe that this is the same mechanism that Processing.js employees to invoke its functions.(4 votes)
- hello guys, i need help,all the challenges above concerning animations have been tricky for me and i have failed to complete any, for the stopwatch challenge i stopped on stage 2 and for the catwalk i failed totally,someone help me(1 vote)
- why did you stop on stopwatch stage two all you have to do is push the stop button(4 votes)
- How do I make it so when I click a button, more words show up?(2 votes)
- 1. Create more text.
2. Append to the body.
You can do all this using jQuery. Or just use regular JS.(3 votes)
- Hi, I haven't been able to come up with code for Catwalk challenge. I am pretty confused as to how to approach the new left position.(2 votes)
- This code worked for me:
<script>
var catEl = document.getElementById("cat");
var startTime = new Date().getTime();
var walkTheCat = function() {
var currTime = new Date().getTime();
var secondsElapsed = ((currTime - startTime)/1000);
var newLeft = secondsElapsed*100;
catEl.style.left = newLeft + "px";
window.requestAnimationFrame(walkTheCat);
};
walkTheCat();
</script>(3 votes)
- Can someone show me the code for Challange: Stopwatch. It is so confuziling!(1 vote)
- <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Challenge: Stopwatch</title>
</head>
<body>
<button id="stop-button" type="button">Stop</button>
<p>
<span id="seconds">0</span> seconds have gone by!
</p>
<script>
// Make it count up on a timer, calling this function
var seconds = document.getElementById("seconds");
var countUp = function() {
seconds.textContent = parseFloat(seconds.textContent) + 1;
};
// How can you make it stop counting?
var stopCountUp = function() {
window.clearInterval(t);
};
var stopButton = document.getElementById("stop-button");
stopButton.addEventListener("click", stopCountUp);
var t = window.setInterval(countUp, 1000);
</script>
</body>
</html>(4 votes)
- How do you make it so that if you scroll, an image follows the scrolling?(1 vote)
- Use CSS
position : fixed;
If you’re talking about a parallax you image, you do something a little differentbackground-image : url(your image url here);
background-attachment : fixed;(3 votes)
- I hate web animation what the heck is going on didn't understand anything about animation.(1 vote)
- To provide an answer for anyone looking for an explanation:
Animation is the process of showing a bunch of images in sequence to show motion. From a mathematical standpoint, we're essentially defining a functionp(t)
, wheret
describes the time from the start of the animation, and the outputp
is the position of the object in question. The trick then is to determinet
on each frame.
setInterval is easy, because the time between frames is constant. Therefore, the input t can be defined ast = t_prev + Δt,
wheret_prev
is the time the previous frame fired at, andΔt
is the interval of time between frames. Therefore, you could calculate the time something like this:// Call before beginning animation:
var t = 0;
...
// Call at the start of each frame:
var t += <insert interval>
requestAnimationFrame is a bit more complicated, because you have to figure out the amount of time elapsed on the fly. You'd need to somehow reference the current time using a function likeDate.now()
. Therefore, you need to calculate the time something like this:// Call before beginning animation:
var tStart = Date.now();
...
// Call at the start of each frame:
var tNow = Date.now() - tStart;
Where tNow is the number of milliseconds since the animation started.
Once you determine the time input, you can use that to calculate the position of the object on screen. Due to the fast refresh rate, the object appears to move continuously, and thus animation.(2 votes)
- does the browser name "Brave" will work?(1 vote)