IAM CodeTrove

How to Create Animations using Javascript

Learn how to create animations using JavaScript.


A Basic Web Page

To demonstrate how to create HTML animations with JavaScript, we can use a simple web page.


CODE:


<!DOCTYPE html>
<html>
<body><h1>My First JavaScript Animation</h1><div id ="myContainer">
<div id ="myAnimation">My animation will go here</div>
</div>

</body>
<html>


Styling the Elements

To make an animation possible, the animated element must be animated relative to a "parent container".

The container element should be created with style = "position: relative".

The animation element should be created with style = "position: absolute".


CODE:


#myContainer {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#myAnimation {
width: 50px;
height: 50px;
position: absolute;
background: red;
}


The Animation Code

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.

The basic code is:


CODE:


var id = setInterval(frame, 5);

function frame() {
if (/* test for finished */) {
clearInterval(id);
} else {
/* code to change the element style */
}
}


Create the Animation Using JavaScript

CODE:

function myMove() { var elem = document.getElementById("myAnimation"); var pos = 0; var id = setInterval(frame, 10); function frame() { if (pos == 350) { clearInterval(id); } else { pos++; elem.style.top = pos + 'px'; elem.style.left = pos + 'px'; } } }

FULL CODE:
<!DOCTYPE html> <html> <style> #myContainer { width: 400px; height: 400px; position: relative; background: yellow; } #myAnimation { width: 50px; height: 50px; position: absolute; background-color: red; } </style> <body>

<p>
<button onclick="myMove()">Click Me</button>
</p>

<div id ="myContainer">
<div id ="myAnimation"></div>
</div>

<script>
function myMove() {
var elem = document.getElementById("myAnimation");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
</script>

</body>
</html>


Back to CodeTrove

Resources
IAM Podcast

IAM Podcast

Growing archive of series and episodes that dive into issues surrounding information access and management. Great place to get the latest IAM News. Great guest speakers.

IAM CodeTrove

IAM CodeTrove

Tired of having to constantly qualify for a number of points to access a community for coding advice and snippets? We were too, so we created this. Have at it!

IAM Network

IAM Network

A growing community with access to communication tools, knowledge base, blog posts, and podcasts on everything about information access and management.