Coding Animations by Using JavaScript - HTML5 APPLICATIONS DEVELOPMENT MANUAL (2016)

HTML5 APPLICATIONS DEVELOPMENT MANUAL (2016)

27 - Coding Animations by Using JavaScript

Animation is the modification of static images to create the effect of movement. Animation can be used to dynamically move objects in the user interface. We can leverage JavaScript to create powerful animations.

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

<!DOCTYPE html>

<html>

<head>

<title></title>

</head>

<body>

<h2>My First JavaScript Animation</h2>

<div id="animate">My animation will go here</div>

</body>

</html>

All animations should be relative to a container element.

<!DOCTYPE html>

<html>

<head>

<title></title>

</head>

<body>

<h2>My First JavaScript Animation</h2>

<div id="container">

<div id="animate">My animation will go here</div>

</div>

</body>

</html>

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

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

<!DOCTYPE html>

<html>

<head>

<title></title>

<style>

#container {

width: 400px;

height: 400px;

position: relative;

background: yellow;

}

#animate {

width: 50px;

height: 50px;

position: absolute;

background: red;

}

</style>

</head>

<body>

<h2>My First JavaScript Animation</h2>

<div id="container">

<div id="animate">My animation will go here</div>

</div>

</body>

</html>

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.

<!DOCTYPE html>

<html>

<head>

<title></title>

<style>

#container {

width: 400px;

height: 400px;

position: relative;

background: yellow;

}

#animate {

width: 50px;

height: 50px;

position: absolute;

background-color: red;

}

</style>

</head>

<body>

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

<div id="container">

<div id="animate"></div>

</div>

<script>

function myMove() {

var elem = document.getElementById("animate");

var pos = 0;

var id = setInterval(frame, 5);

function frame() {

if (pos == 350) {

clearInterval(id);

} else {

pos++;

elem.style.top = pos + 'px';

elem.style.left = pos + 'px';

}

}

}

</script>

</body>

</html>