JavaScript HTML DOM Animation
Discover how to make HTML animations with JavaScript.
A Basic Web Page
To show how you can make HTML animations using JavaScript, we'll use a basic webpage:
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 must be in relation to a container element.
Example
<div id ="container">
<div id ="animate">My
animation will go here</div>
</div>
Style the Elements
The box should be made using the style attribute as position: relative
.
The animation part needs to be made using the style attribute with position: absolute
.
Animation Code
In JavaScript, animations are created by coding step-by-step adjustments to how an element looks.
The modifications occur through a timer. If the timer's duration is short, the animation appears to flow seamlessly.
Here is the fundamental code:
Example
id = setInterval(frame, 5);
function frame() {
if (/*
test for finished */) {
clearInterval(id);
} else {
/* code to change the element style */
}
}