Loading lesson path
Learn to create HTML animations using JavaScript.
To demonstrate how to create HTML animations with JavaScript, we will use a simple web page:
<!DOCTYPE html> <html> <body>
Formula
< h1 > My FirstJavaScript Animation</h1> <div id="animation">My animation will go here</div> </body> </html>
All animations should be relative to a container element.
<div id ="container"> <div id ="animate">My animation will go here</div> </div>
The container element should be created with style = " position: relative ". The animation element should be created with style = " position: absolute ".
#container {
width: 400px;height:
400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;height:
50px;
position: absolute;
background: red;
}JavaScript animations are done by programming gradual changes in an element's style. The changes are called by a timer. When the timer interval is small, the animation looks continuous.
Example id = setInterval(frame, 5);
function frame() {
if (/*
test for finished */) {
clearInterval(id);
} else {/* code to change the element style */
}
}Example function myMove() {
let id = null;
const elem = document.getElementById("animate");
let pos = 0;
clearInterval(id);
id = setInterval(frame, 5);
function frame() {
if (pos ==
350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}