Javascript – JavaScript Animation – Javascript Tutorial

In this article, we are going to discuss JavaScript animation with its functions.

What is JavaScript Animation?

JavaScript animations are done by incremental programming changes in the style of an element. JavaScript animations can perform tasks that CSS cannot. JavaScript could be used to transfer several DOM elements across the page in accordance with a logical equation or function. JavaScript includes the three functions mentioned below, which are commonly used in animation programs.

setTimeout (function, duration): This function can be used to call the function after a millisecond delay.
setInterval (function, duration): This function can be used to call the function after each duration milliseconds.
clearTimeout (setTimeout_variable): This function can be used to clear the timer that has been set by the setTimeout()

JavaScript can also modify a DOM object”s attributes, such as its location on the screen. An object”s top and left attributes can be set to place it anywhere on the frame. The syntax of JavaScript may be defined as:

// Set the distance from the left side of the screen.  
object.style.left = distance in pixels or points;   
and  
// Set the distance from the top side of the screen.  
object.style.top = distance in pixels or points;  

Example:

Let”s take a basic example to understand how we can create a basic JavaScript Animation web page.

<!DOCTYPE html>  
<html>  
  <head>  
    <title>JavaScript Animation</title>  
  </head>  
<body>  
<h1>My First JavaScript Animation</h1>  
<div id ="myContainer">  
    <div id ="myAnimation">My first animation is here</div>  
</div>  
</body>  
<html>  

Output: After executing this code, we will get the output as shown below in the screenshot.

Styling the elements

Let”s take another example to show the animation by styling the elements. Here, we make a container element with the help of style = “position: relative” and make an animated element in the container element with the help of style = “position: absolute”.

Example:

<!Doctype html>  
<html>  
  <head>  
    <title>JavaScript Animation</title>  
  </head>  
<style>  
#myContainer {  
  width: 350px;  
  height: 350px;  
  position: relative;  
  background: green;  
}  
#myAnimation {  
  width: 45px;  
  height: 45px;  
  position: absolute;  
  background: blue;  
}  
</style>  
<body>  
<h1>My First JavaScript Animation</h1>  
<div id="myContainer">  
<div id="myAnimation"></div>  
</div>  
</body>  
</html>  

Output: After executing this code, we will get the output as shown below in the screenshot.

Example:

Let”s take another example to understand that how we can create an animation in JavaScript.

<!DOCTYPE html>  
<html>  
  <head>  
    <title>JavaScript Animation</title>  
  </head>  
<style>  
#myContainer {  
  width: 350px;  
  height: 350px;  
  position: relative;  
  background: green;  
}  
#myAnimation {  
  width: 45px;  
  height: 45px;  
  position: absolute;  
  background-color: rgb(226, 43, 43);  
}  
</style>  
<body>  
<p>  
<button onclick="myMove()">Click Here</button>   
</p>  
<div id ="myContainer">  
<div id ="myAnimation"></div>  
</div>  
<script>  
var id = null;  
function myMove() {  
  var elem = document.getElementById("myAnimation");     
  var pos = 0;  
  clearInterval(id);  
  id = setInterval(frame, 10);  
  function frame() {  
    if (pos == 300) {  
      clearInterval(id);  
    } else {  
      pos++;   
      elem.style.top = pos + 'px';   
      elem.style.left = pos + 'px';   
    }  
  }  
}  
</script>  
</body>  
</html>  

Output: After executing this code, we will get the output as shown below in the screenshot.

As we have above seen in the screenshot, there is a “Click Here” button. When we click on the button, the image is animated from the top left side corner to the bottom left side corner, as seen in the screenshot.

Manual Animation

Now, using the DOM object properties and JavaScript functions, let”s take a simple animation example.

Example:

<!DOCTYPE html>  
<html>     
   <head>  
      <title>JavaScript Animation</title>    
      <h1>JavaScript Animation</h1>      
      <script type = "text/javascript">  
         <!--  
            var imgObj = null;  
            function init() {  
               imgObj = document.getElementById('myImage');  
               imgObj.style.position= 'relative';   
               imgObj.style.left = '0px';   
            }  
            function moveRight() {  
               imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';  
            }  
            window.onload = init;  
         //-->  
      </script>  
   </head>  
   <body>     
      <form>  
         <img id = "myImage" src = "/C:\Users\hp\Downloads\images.jpg" />  
         <p>Click the button below to move the image left to right</p>  
         <input type = "button" value = "Click Here" onclick = "moveRight();" />  
      </form>        
   </body>  
</html>  

Output: After executing this code, we will get the output as shown below in the screenshot.

As we have seen in the screenshot, there is a “Click Here” button. When we click on the button, the image is moves left to right at every click, as shown in the screenshot.

Explanation

To get a DOM object, we use the JavaScript function getElementById() and then allocate it to the global variable imgObj.
To initialize imgObj, we defined an initialization function init(), where we set its location and left attributes.
When the window loads, we call the initialization function.
Finally, we use the moveRight() function to add 10 pixels to the left To switch it to the left, we might set it to a negative value.

Automated Animation

In the previous example, we have seen how the image shifts to the right side of the screen with each click. We may automate this method by using the JavaScript function setTimeout(), which looks like this:

Example:

Let”s take an example to explain that how we may make a JavaScript automated animation.

<!DOCTYPE html>  
<html>     
   <head>  
      <title>JavaScript Animation</title>        
      <script type = "text/javascript">  
         <!--  
            var imgObj = null;  
            var animate ;   
            function init() {  
               imgObj = document.getElementById('myImg');  
               imgObj.style.position= 'relative';   
               imgObj.style.left = '0px';   
            }  
            function moveRight() {  
               imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';  
               animate = setTimeout(moveRight,12);   
            }  
            function stop() {  
               clearTimeout(animate);  
               imgObj.style.left = '0px';   
            }  
            window.onload = init;  
         //-->  
      </script>  
   </head>  
   <body>     
     <h1>JavaScript Automated Animation</h1>  
      <form>  
        <p>Click the buttons below to manage the automated animation</p>  
         <img id = "myImg" src = "/C:\Users\hp\Downloads\images.jpg" />  
         <input type = "button" value = "Start" onclick = "moveRight();" />  
         <input type = "button" value = "Stop" onclick = "stop();" />  
      </form>        
   </body>  
</html>  

Output: After executing the above code, we will get the output as shown below in the screenshot.

As we have seen in the above screenshot, there is a start and stop button. When we click on the start button, the image is animated to the right side. If we click on the stop button, the image is positioned in its original position.

Explanation:

In this example, we may add two another method that helps to make animation automated. These methods are as follows:

moveRight(): To set the position of imgObj, the moveRight() method calls the setTimeout()
Stop(): We"ve added a new function stop(), that resets the object to its original state and clears the timer set by the setTimeout()