JavaScript HTML DOM Animation
Learn how to create HTML animations using JavaScript.
A Basic Web Page
To demonstrate how to create HTML animations with JavaScript, let's start with a simple web page:
Example
<!DOCTYPE html>
<html>
<body><h1>My First JavaScript Animation</h1>
<div id="animation">My animation will go here</div>
</body>
</html>
Create an Animation Container
All animations should be relative to a container element.
Example
<div id="container">
<div id="animate">My animation will go here</div>
</div>
Style the Elements
The container element should have style = "position: relative", and the animation element should have style = "position: absolute".
Example
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background: red;
}
</style>
Animation Code
JavaScript animations are created by programming gradual changes to an element's style. These changes are triggered by a timer. When the timer interval is small, the animation appears smooth.
The basic code structure for creating an animation is:
Example
id = setInterval(frame, 5);
function frame() {
if (/* test for finished */) {
clearInterval(id);
} else {
/* code to change the element style */
}
}
Create the Full Animation Using JavaScript
Here is an example of a complete animation function in JavaScript:
Example
<!DOCTYPE html>
<html>
<head>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background: red;
}
</style>
</head>
<body>
<h1>My First JavaScript Animation</h1>
<div id="container">
<div id="animate"></div>
</div>
<script>
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';
}
}
}
myMove();
</script>
</body>
</html>